在csv文本中查找单词

时间:2019-03-28 11:37:30

标签: python csv

我的Python代码有问题。我想找出csv中某个单词的出现,但不知何故出现的次数没有扩大:

occurences = 0
with open ("text.csv", "r") as text:
    for line in text:
        splitted = line.strip().split(' ')
        print(splitted)

    if splitted == 'bike':
        continue 
        occurences = occurences + int(splitted)

print(occurences)

即使自行车在文本中出现3次,输出也为0。 在此先感谢您,我是Python初学者,您的解决方案可能很简单:-)

Finn

4 个答案:

答案 0 :(得分:0)

您在这里:

x = ['this is a bike yo bike hahahaha bike','no bike here']
occurences = 0
for line in x:
    splitted = line.strip().split(' ')
    print(splitted)

    if 'bike' in splitted:
#           continue 
        occurences = occurences + splitted.count('bike')

print(occurences)

答案 1 :(得分:0)

尝试一下:

occurences = 0
with open ("text.csv", "r") as text:
    for line in text:
        splitted = line.strip().split(' ')
        print(splitted)

        count = splitted.count('bike')
        occurences = occurences + count

print(occurences)

答案 2 :(得分:0)

使用str.count()

test.csv:

bike no more car bike
car car car
hello car
okay bike
what is this bike

因此

with open("test.csv") as f:
    contents = f.read()
    occurences = contents.count("bike")    
print(occurences)   # 4

编辑

单线:

print([sum(line.count("bike") for line in open('test.csv'))][0]) # 4

答案 3 :(得分:0)

以下是使用collections.Counter的替代方法:

from collections import Counter
occurrences = Counter()
with open ("text.csv", "r") as text:
    for line in text:
        occurrences.update(line.strip().split())
print(ocurrences['bike'])