开发者

prints line number in both txtfile and list?

开发者 https://www.devze.com 2023-01-01 00:22 出处:网络
i have this code which prints the line number in infile butalso the linenumber in words what do i do to only print the line number of the txt file next to the words???

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:

  1. 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):
    
  2. 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)
    
  3. Also note that the above code snippet is exactly what defaultdicts 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)
    
  4. 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)
0

精彩评论

暂无评论...
验证码 换一张
取 消