Python:计算一个单词在文件中出现的次数 [英] Python: Count how many times a word occurs in a file

查看:1342
本文介绍了Python:计算一个单词在文件中出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其中包含城市名称,然后在文件中每行的状态名称。例如,如果我的文件包含:


$ b。如果我的文件包含:

 洛杉矶加州
圣地亚哥加州
旧金山加州
奥尔巴尼纽约
布法罗纽约
奥兰多佛罗里达州

我假设要返回每个州名称发生多少次。

  for f:
California_count = line.find(California)
if California_count!= - 1:
total = line.count(California)
print(total)

这只给我值1,我假设是因为它每行出现1次。如何让它返回数字3而不是数字1?

解决方案

  total = 0 

with open .txt')as f:
for line in f:
finded = line.find('California')
if founded!= -1 and finded!= 0:
total + = 1

print total

输出:

  3 


I have a file that contains a city name and then a state name per line in the file. I am suppose to count how many times a state name occurs and return the value.

for example, if my file contained:

Los Angeles   California
San Diego     California
San Francisco California
Albany        New York
Buffalo       New York
Orlando       Florida

I am suppose to return how many times each state name occurs. I have this for California.

for line in f:
    California_count=line.find("California")
    if California_count!=-1:
        total=line.count("California")
print(total)

This only gives me the value 1, which I am assuming is because it occurs 1 time per line. How do I get it to return the number 3 instead of the number 1?

解决方案

total = 0

with open('input.txt') as f:
    for line in f:
        finded = line.find('California')
        if finded != -1 and finded != 0:
            total += 1

print total

output:

3

这篇关于Python:计算一个单词在文件中出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆