I have a file, called input.py, which contains the following:
#This is a file of categories
Animals: cat, dog, frog, cheetah, tiger
Items: desk, chair, bus, cups, pencil
Technology: cellphone, TV, laptop, wifi-router
#That's the end of the file
and I want to filter out all blank lines and lines starting with # to produce output.py:
Animals: cat, dog, frog, cheetah, tiger
Items: desk, chair, bus, cups, pencil
Technology: cellphone, TV, laptop, wifi-router
My code is
with open('input.py', 'r') as infile, open('output.py', 'w') as outfile:
for line in infile:
if line[0].strip('') == '#' or line == '\n':
pass
else:
outfile.write(line)
but it doesn't strip off the line starting with a tab. I've tried replacing .strip('') with .strip('\t') but I get the same output:
Animals: cat, dog, frog, cheetah, tiger
Items: desk, chair, bus, cups, pencil
Technology: cellphone, TV, laptop, wifi-router
#That's the end of the file
Why is .strip('') or .strip('\t') not stripping off the tab?
Strip method can only remove characters from beginning or end of the string. Try using replace instead.
>>> line = "Animals: cat, dog, frog, cheetah, tiger"
>>> line.replace('\t', ' ')
'Animals: cat, dog, frog, cheetah, tiger'
You have forgotten to actually apply strip for applicable lines in your else condition. In addition, use str.startswith to test for whether your line begins with a specific string.
Here's a complete example:
from io import StringIO
mystr = StringIO("""Animals: cat, dog, frog, cheetah, tiger
Items: desk, chair, bus, cups, pencil
Technology: cellphone, TV, laptop, wifi-router
#That's the end of the file""")
with mystr as infile:
for line in infile:
if line.strip().startswith('#') or line == '\n':
pass
else:
print(line.strip())
Result:
Animals: cat, dog, frog, cheetah, tiger
Items: desk, chair, bus, cups, pencil
Technology: cellphone, TV, laptop, wifi-router
Related
The following code block will not accept a multi line comment for the whole block using """ - I suspect this is because three double quotes have been used for a string to span multiple lines as part of this code block.
"""
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)
"""
Are there any alternative methods to ensure this code block is commented out?
I show the problem by an arrow in your code:
"""
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
""" <-----------------------------------------DELETE THIS ONE OR ADD ANOTHER ONE
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)
"""
I'm using bibtexparser to parse a bibtex file.
import bibtexparser
with open('MetaGJK12842.bib','r') as bibfile:
bibdata = bibtexparser.load(bibfile)
While parsing I get the error message:
Could not parse properly, starting at
#article{Frenn:EvidenceBasedNursing:1999,
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/pyparsing.py", line 3183, in parseImpl
raise ParseException(instring, loc, self.errmsg, self)
pyparsing.ParseException: Expected end of text (at char 5773750),
(line:47478, col:1)`
The line refers to the following bibtex entry:
#article{Frenn:EvidenceBasedNursing:1999,
author = {Frenn, M.},
title = {A Mediterranean type diet reduced all cause and cardiac mortality after a first myocardial infarction [commentary on de Lorgeril M, Salen P, Martin JL, et al. Mediterranean dietary pattern in a randomized trial: prolonged survival and possible reduced cancer rate. ARCH INTERN MED 1998;158:1181-7]},
journal = {Evidence Based Nursing},
uuid = {15A66A61-0343-475A-8700-F311B08BB2BC},
volume = {2},
number = {2},
pages = {48-48},
address = {College of Nursing, Marquette University, Milwaukee, WI},
year = {1999},
ISSN = {1367-6539},
url = {},
keywords = {Treatment Outcomes;Mediterranean Diet;Mortality;France;Neoplasms -- Prevention and Control;Phase One Excluded - No Assessment of Vegetable as DV;Female;Phase One - Reviewed by Hao;Myocardial Infarction -- Diet Therapy;Diet, Fat-Restricted;Phase One Excluded - No Fruit or Vegetable Study;Phase One Excluded - No Assessment of Fruit as DV;Male;Clinical Trials},
tags = {Phase One Excluded - No Assessment of Vegetable as DV;Phase One Excluded - No Fruit or Vegetable Study;Phase One - Reviewed by Hao;Phase One Excluded - No Assessment of Fruit as DV},
accession_num = {2000008864. Language: English. Entry Date: 20000201. Revision Date: 20130524. Publication Type: journal article},
remote_database_name = {rzh},
source_app = {EndNote},
EndNote_reference_number = {4413},
Secondary_title = {Evidence Based Nursing},
Citation_identifier = {Frenn 1999a},
remote_database_provider = {EBSCOhost},
publicationStatus = {Unknown},
abstract = {Question: text.},
notes = {(0) abstract; commentary. Journal Subset: Core Nursing; Europe; Nursing; Peer Reviewed; UK \& Ireland. No. of Refs: 1 ref. NLM UID: 9815947.}
}
What is wrong with this entry?
It seems that the issue has been addressed and resolved in the project repository (see Issue 147)
Until the next release, installing the library from the git repository can serve as a temporary fix.
pip install --upgrade git+https://github.com/sciunto-org/python-bibtexparser.git#master
I had this same error and found an entry near the line mentioned in the error that had a line like this
...
year = {1959},
month =
}
When I removed the null month item it parsed for me.
Installed imdbpy and tried running the default examples mentioned on -http://imdbpy.sourceforge.net/support.html, but I am unable to run them successfully.
Program:
# Create the object that will be used to access the IMDb's database.
ia = imdb.IMDb() # by default access the web.
# Search for a movie (get a list of Movie objects).
s_result = ia.search_movie('The Untouchables')
# Print the long imdb canonical title and movieID of the results.
for item in s_result:
print item['long imdb canonical title'], item.movieID
# Retrieves default information for the first result (a Movie object).
the_unt = s_result[0]
ia.update(the_unt)
# Print some information.
print the_unt['runtime']
print the_unt['rating']
director = the_unt['director'] # get a list of Person objects.
# Get the first item listed as a "goof".
ia.update(the_unt, 'goofs')
print the_unt['goofs'][0]
# The first "trivia" for the first director.
b_depalma = director[0]
ia.update(b_depalma)
print b_depalma['trivia'][0]
Error:
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/karan/PycharmProjects/IMDBParser/extractor/imdbpy_tester.py
Untouchables, The (1987) 0094226
Untouchables (in development), The (????) 1987680
"Untouchables, The" (1959) 0052522
"Untouchables, The" (1993) 0106165
Intouchables, The (2011) 1675434
Untouchables, The (2017) 1877895
Untouchable (I) (2016) 5509634
Untouchable 2, The (2001) (VG) 0287778
"Untouchable" (2015) 4191792
Untouchable, The (1997) (VG) 0287779
Untouchable (2012) 2266916
"Untouchable" (2017) (mini) 5220680
Untouchable (I) (2010) 1590231
Untouchable (III) (2013) 3001590
Untouchables, The (1991) (VG) 0335509
"Frontline" The Untouchables (2013) 2620144
"DVD_TV: Enhanced Version" The Untouchables (2005) 1088289
"Real Story, The" The Untouchables (2009) 2760176
"Harbour Lights" The Untouchables (1999) 0596815
"Bill, The" The Untouchables (2000) 0525783
[u'119']
7.9
Traceback (most recent call last):
File "/Users/karan/PycharmProjects/IMDBParser/extractor/imdbpy_tester.py", line 27, in <module>
print the_unt['goofs'][0]
File "/Library/Python/2.7/site-packages/IMDbPY-5.0-py2.7-macosx-10.11-intel.egg/imdb/utils.py", line 1469, in __getitem__
rawData = self.data[key]
KeyError: 'goofs'
Process finished with exit code 1
I found sth similar posted by another user here - https://bitbucket.org/alberanid/imdbpy/issues/42/examples-not-functional but I do not know how to fix this problem.
I'm very new to python/programing, and, i've been playing with a small random choice generator. I'm really happy with how everything is working so far, but I'm having a problem with the if statement. how do I go about signaling that the if should point to the first generated choice from table Desert, and not generate a second choice? I've tried nesting the if statement in the print command, but got a lot of syntax errors. Here is the code:
import random
import sys
Name = ['Dave', 'Suzane', 'Jim', 'Diana']
Appitizers = ['Spinach & Artichoke Dip', 'Crispy Green Beans', 'Half Chicken Quesadila', 'None, for me, just the main course please']
MainCourse = ['Steak', 'Sea Food', 'Grilled Chicken', 'House Salad', 'Rib Sanwich', 'Soup of the Day']
Desert = ['Pie of the Day', 'Chocolate Moose', 'Cheeze Cake', "No Thanks, I'm Full!"]
Goodbye = ['Captian', 'Monsiure', 'Sir', 'Madame',]
Goodbye2 = ['Come back again!', 'See you soon', 'Thank you for stopping by', 'Thank you for choosing us!']
print("Hello ", random.choice(Name), "tonight you're meal will be:")
print("Appitizer:", random.choice(Appitizers))
print("Followed by Main Coure:", random.choice(MainCourse))
print("And finally Desert:", random.choice(Desert))
if random.choice(Desert)=="No Thanks, I'm Full!": print('Farwell!', random.choice(Goodbye1)), sys.exit()
print(random.choice(Goodbye2))
Thanks!
Assign the result of random.choice(Desert) to a variable, and use it in both places where it's applicable. (and while you're at it, change Goodbye1 to a variable that exists, such as Goodbye)
x = random.choice(Desert)
print("And finally Desert:", x)
if x=="No Thanks, I'm Full!":
print('Farwell!', random.choice(Goodbye))
sys.exit()
I am writing a script that works like google suggest. Problem is that I am trying to get a suggestion for next 2 most likely words.
The example uses a txt file working_bee.txt. When writing a text "mis" I should get suggestions like "Miss Mary , Miss Taylor, ...". I only get "Miss, ...". I suspect the Ajax responseText method gives only a single word?
Any ideas what is wrong?
# Something that looks like Google suggest
def count_words(xFile):
frequency = {}
words=[]
for l in open(xFile, "rt"):
l = l.strip().lower()
for r in [',', '.', "'", '"', "!", "?", ":", ";"]:
l = l.replace(r, " ")
words += l.split()
for i in range(len(words)-1):
frequency[words[i]+" "+words[i+1]] = frequency.get(words[i]+" "+words[i+1], 0) + 1
return frequency
# read valid words from file
ws = count_words("c:/mod_python/working_bee.txt").keys()
def index(req):
req.content_type = "text/html"
return '''
<script>
function complete(q) {
var xhr, ws, e
e = document.getElementById("suggestions")
if (q.length == 0) {
e.innerHTML = ''
return
}
xhr = XMLHttpRequest()
xhr.open('GET', 'suggest_from_file.py/complete?q=' + q, true)
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
ws = eval(xhr.responseText)
e.innerHTML = ""
for (i = 0; i < ws.length; i++)
e.innerHTML += ws[i] + "<br>"
}
}
xhr.send(null)
}
</script>
<input type="text" onkeyup="complete(this.value)">
<div id="suggestions"></div>
'''
def complete(req, q):
req.content_type = "text"
return [w for w in ws if w.startswith(q)]
txt file:
IV. Miss Taylor's Working Bee
"So you must. Well, then, here goes!" Mr. Dyce swung her up to his shoulder and went, two steps at a time, in through the crowd of girls, so that he arrived there first when the door was opened. There in the hall stood Miss Mary Taylor, as pretty as a pink.
"I heard there was to be a bee here this afternoon, and I've brought Phronsie; that's my welcome," he announced.
"See, I've got a bag," announced Phronsie from her perch, and holding it forth.
So the bag was admired, and the girls trooped in, going up into Miss Mary's pretty room to take off their things. And presently the big library, with the music-room adjoining, was filled with the gay young people, and the bustle and chatter began at once.
"I should think you'd be driven wild by them all wanting you at the same minute." Mr. Dyce, having that desire at this identical time, naturally felt a bit impatient, as Miss Mary went about inspecting the work, helping to pick out a stitch here and to set a new one there, admiring everyone's special bit of prettiness, and tossing a smile and a gay word in every chance moment between.
"Oh, no," said Miss Mary, with a little laugh, "they're most of them my Sunday- school scholars, you know."
Looking at your code I believe you are not sending the correct thing to Apache. You are sending apache a list and apache is expecting a string. I would suggest changing your return to json:
import json
def complete(req, q):
req.content_type = "text"
return json.dumps([w for w in ws if w.startswith(q)])