繁体   English   中英

Python - 文件处理,for 循环

[英]Python - file handling, for loop

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)

When I run this code I get this:
 Type word: asd
 Type word: asd
 Type word: asd
 Type word: asd
 Type word: sad
 Type word: asd
 Type word: asd

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

我不确定您要计算什么,因此请随意根据您的问题进行调整,但是您可以遍历每一行并计算单词数以保存它们,然后再运行另一个 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: "))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM