【问题标题】:count characters in a word in text file python and write those characters into a csv file计算文本文件python中单词中的字符并将这些字符写入csv文件
【发布时间】:2017-04-19 00:38:02
【问题描述】:

我有一个文本文件 test.txt,其中包含 apple、ant、dog、cat、son 等单词。我希望 python 计算文本文件中所有单词的字符总数

Eg:
Word Letters
Ant   3
Apple 5
Dog   3
Cat   3
Son   3

这是我尝试过的:

string = open('file.txt').read()

for word in string.split():
    print len(word)

【问题讨论】:

  • 你能提供一个你已经尝试过的例子吗?
  • 不是上述问题的重复,因为它打印每个字母的数量,而我正在寻找文本文件中的每个单词,我无法得到

标签: string python-2.7


【解决方案1】:

如果你每行有一个单词,你可以使用这个:

def main():
string = open('Newfile.txt').read()
for word in string.split():
    print ("{} {}".format(word, len(word)))
main()

Try it here

【讨论】:

  • 我正在寻找一种更短更高效的代码来读取文本文件中的所有单词并打印每个单词中的字符数
  • 很高兴为您提供帮助
  • 你能解释一下如何将这些字符串写入 csv 文件吗?
  • 请将它作为一个新问题发布,因为它是另一个主题,也避免长时间讨论评论:)
【解决方案2】:

要补充 Reda Maachi 的答案,如果您在文本文档中多次出现相同的单词,您可以将拆分字符串转换为 set。 Iv 还包括一行,如果您有混合大小写,则将所有单词转换为小写。

string = string.split()
string = [x.lower() for x in string]
string = set(string)

【讨论】:

    【解决方案3】:

    你可以使用Collections

    from collections import Counter
    file=open('file.txt','r')
    words = Counter(file.read().split())
    for item in words.items():
        print("{}\t{}".format(*item))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 2021-06-25
      • 2013-02-20
      • 2020-10-01
      • 1970-01-01
      相关资源
      最近更新 更多