【问题标题】:count letters and words in a file with python [closed]用python计算文件中的字母和单词[关闭]
【发布时间】:2020-10-04 15:01:51
【问题描述】:

代码应该从文件“input.txt”中读取文本,然后计算每行中的字母和单词的数量,然后将输出写入一个名为“output.txt”的新文件

我需要帮助编写上述问题的代码。

【问题讨论】:

标签: python python-3.x python-2.7 file-manipulation


【解决方案1】:
import sys

fname = sys.argv[1]
lines = 0
words = 0
letters = 0

for line in open(fname):
    lines += 1
    letters += len(line)

    pos = 'out'
    for letter in line:
        if letter != ' ' and pos == 'out':
            words += 1
            pos = 'in'
        elif letter == ' ':
            pos = 'out'

print("Lines:", lines)
print("Words:", words)
print("Letters:", letters)

试试这个然后告诉我

【讨论】:

    【解决方案2】:

    没有关于什么单词的详细信息,因此假设任何用空格分隔的项目都将是一个单词。任何其他特殊字符如果以空格分隔,也将是一个单词。

    试试这个:

    with open('input.txt', 'rt') as f:
        lines = f.readlines()
    
    result = []
    for line in lines:
        length = len(line)
        words = len(line.strip().split())
        result.append(', '.join([str(length), str(words)]))
    
    with open('output.txt', 'wt') as f:
        f.write('\n'.join(result))
    

    【讨论】:

      猜你喜欢
      • 2014-01-02
      • 2012-10-16
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-01
      • 2021-12-12
      相关资源
      最近更新 更多