【问题标题】:Writing number of occurrences to a file将出现次数写入文件
【发布时间】:2015-04-23 11:20:20
【问题描述】:

我正在计算列表中单词的出现次数(称为 a_master)。要搜索和计数的单词在 dictionary.txt 中。问题是,当我将计数写入文件时,结果如下:

1Count cloud
19Count openstack
3 

这里是代码:

with open("dictionary.txt","r") as f:
for line in f:
    if a_master.count(line.strip()) !=0:
        file.write( "Count " + line + str((a_master).count(line.strip())))

如你所见,由于某种原因,当它输出数字时,它把它放在一个新的行上,我不知道为什么!

【问题讨论】:

标签: python


【解决方案1】:

在线使用.strip()。

试试这个

with open("dictionary.txt","r") as f:
for line in f:
    if a_master.count(line.strip()) !=0:
        file.write( "Count " + line.strip() + str((a_master).count(line.strip())))

【讨论】:

  • 更高效地只执行一次操作并设置 line=line.strip() 和 n=a_master.count(line)
猜你喜欢
  • 2020-02-16
  • 1970-01-01
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多