所以這是我嘗試查找用戶輸入的單詞并查找包含該單詞的行數的代碼,如果沒有行包含未找到的單詞輸出,但是當我輸入我知道檔案中存在的單詞時,它回傳 0不僅檔案中的單詞它甚至沒有像我想要的那樣輸出。(這是我的代碼)
response = input('Please enter words: ')
letters = response.split()
count = 0
with open("alice.txt", "r", encoding="utf-8") as program:
for line in program:
if letters in line:
count = 1
if(count < 1):
print("not found")
print(count)
uj5u.com熱心網友回復:
你在做什么是行不通的 split 函式回傳一個字串串列,你正在根據單個字串檢查該串列。
這是你想做的嗎?
response = input("Please enter a word: ")
count = 0
with open("alice.txt", 'r') as program:
for line in program:
if response in line:
count = 1
if count == 0:
print("not found")
print(count)
uj5u.com熱心網友回復:
您不需要 split 函式和代碼中 if 條件錯誤的位置。請參考以下代碼。
response = input('Please enter word: ')
count = 0
with open("alice.txt", "r", encoding="utf-8") as program:
for line in program:
if response in line:
count = 1
if count == 0:
print('Not found')
else:
print(count)
uj5u.com熱心網友回復:
您將 txt 檔案作為單行打開,而不是作為單個行的串列打開時遇到問題。
添加“.readlines()”可以解決這個問題!
我還繼續將各個行設定為“行”,然后在新的“行”變數中搜索輸入詞。
response = input('Please enter words: ')
letters = response.split()
count = 0
foo = open(
"alice.txt", "r",
encoding="utf-8").readlines()
for line in foo:
for word in letters:
if word in line:
count = 1
if(count < 1):
print("not found")
else:
print(count)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/337004.html
