【问题标题】:Python - file handling, for loopPython - 文件处理,for循环
【发布时间】:2021-11-14 01:54:02
【问题描述】:
words = []

with open("test.txt", "r") as rfile:
 n_words = rfile.read().count("*")
 for n in range(0, n_words):
   words.append(input("Type word: "))
 for line in rfile.readlines():
   ind = [x for x, ch in enumerate(line) if ch == "*"]
   if ind:
          print(ind)

当我运行这段代码时,我得到了这个: 输入词:asd 输入词:asd 输入词:asd 输入词:asd 输入词:悲伤 输入词:asd 输入单词:asd

程序不运行第二个 for 循环。 无论我先放哪个 for 循环,第二个都没有运行。 有谁知道为什么?

【问题讨论】:

  • 我猜是因为read() 已经消耗了整个文件,所以readlines() 没有任何东西可以处理。
  • "rfile" 已经完全是 "read()",因此 "readlines()" 不再读取(按交换顺序相同)。您必须将文件指针设置为以“seek”方法开头。

标签: python for-loop file-handling


【解决方案1】:

我不确定您要计算什么,因此请随意调整它以适应您的问题,但您可以遍历每一行并计算单词数以保存它们,然后运行另一个 for 循环。 例如,此代码将在每一行中打印"*" 的索引(如果没有,它将不打印任何内容,但不会告诉您哪一行没有),然后要求您输入与有相同数量的单词"*"(单独,如果是另一个字符串的一部分,则不会计算它们)在文件中

words = []
n_lines = 0
n_words = 0

with open("text.txt", mode = "r") as rfile:
    for line in rfile:
        wordlist = line.split()
        n_lines += 1
        n_words += wordlist.count("*")
        ind = [x for x, ch in enumerate(line.split()) if ch == "*"]
        if ind:
            print(ind)
    for n in range(0, n_words):
        words.append(input("Type word: "))

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 2016-04-30
    • 2013-10-07
    • 2023-03-27
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多