【问题标题】:Add row number and word count to end of lines in text file将行号和字数添加到文本文件的行尾
【发布时间】:2021-12-30 22:44:51
【问题描述】:

我无法将我的行号 (i) 和字数 (words) 写入我正在创建的文件的每一行的末尾。

应该像下面这样

猫在

帽子里的猫

变成

猫 0 1

猫在 1 3

戴帽子的猫 2 7

注意:我不能使用导入的函数

def annotate(f_in):
    with open(f_in, 'r') as f:
        with open('annotated.txt', 'w') as f_out:
            words = 0
            for i, line in enumerate(f, start = 0):
                words += len(line.split(' '))
                print(line, i, words)
                f_out.write(line)

【问题讨论】:

  • 究竟发生了哪些您意想不到的事情?似乎您正在将想要的输出打印到控制台,但在写入文件时却没有这样做。如果它在控制台上正确显示但不在文件中,那么这应该是原因。如果不是,请准确解释不应该发生的事情。
  • 我想我可能有点不清楚。 print(line, i, words) f_out.write(line)
  • 所以正如你所说,它没有进入文件。我知道我需要以某种方式更改 f_out.write(line) 以实现它,但我不知道该怎么做

标签: python file row word-count


【解决方案1】:

您可以通过将文件中的每一行附加到一个二维列表并使用列表索引作为行号和嵌入列表的长度作为单词数来做到这一点。

file = open("catinhat.txt", "r")

lines = []
for line in file: 
  stripped_line = line.strip() # strip the line of "\n"
  line_list = stripped_line.split() # make the line into a list of words
  lines.append(line_list) # make 2d list of each line

file.close()

totalWords = 0
for i in range(len(lines)):
    row = i
    noWordsInRow = len(lines[i])
    totalWords+=noWordsInRow
    print(row, totalWords)

这个输出是:

0 1
1 3
2 6
3 10

希望这是你需要的:)

【讨论】:

  • 谢谢!也许我的解释不够清楚。我会尝试更好地解释 :) 我仍然希望显示文本,正如我在上面的示例中提到的那样,但是输出 1) 创建了一个新文件 (f_out) 2) 新文件 f_out 与我的文本具有相同的文本f_in,但在读取每行之后的行数和总单词数。
猜你喜欢
  • 2011-12-01
  • 2020-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-07
相关资源
最近更新 更多