[英]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.