prints line number in both txtfile and list?
i have this code which prints the line number in infile but also the linenumber in words what do i do to only print the line number of the txt file next to the words???
d = {}
counter = 0
wrongwords = []
for line in infile:
infile = line.split()
wrongwords.extend(infile)
counter += 1
for word in infile:
if word not in d:
d[word] = [counter]
if word in d:
d[word].append(counter)
for stuff in wrongwords: print(stuff, d[stuff])
the output is :
hello [1, 2, 7, 9] # this is printing the linenumber of the txt file
hello [1] #开发者_StackOverflow this is printing the linenumber of the list words
hello [1]
what i want is:
hello [1, 2, 7, 9]
Four things:
You can keep track of the line number by doing this instead of handling a counter on your own:
for line_no, word in enumerate(infile):
As sateesh pointed out above, you probably need an
else
in your conditions:if word not in d: d[word] = [counter] else: d[word].append(counter)
Also note that the above code snippet is exactly what
defaultdict
s are for:from collections import defaultdict d = defaultdict(list)
Then in your main loop, you can get rid of the
if..else
part:d[word].append(counter)
Why are you doing
wrongwords.extend(infile)
?
Also, I don't really understand how you are supposed to decide what "wrong words" are. I assume that you have a set named wrongwords
that contains the wrong words, which makes your final code something like this:
from collections import defaultdict
d = defaultdict(list)
wrongwords = set(["hello", "foo", "bar", "baz"])
for counter, line in enumerate(infile):
infile = line.split()
for word in infile:
if word in wrongwords:
d[word].append(counter)
精彩评论