[英]Loop within a loop not re-looping with reading a file Python3
試圖編寫一個能夠在文本文件中找到所有特定類型字符的代碼對於元音,它會找到所有的數字,但不會通過文本重新循環來讀取e。 救命?
def finder_character(file_name,character):
in_file = open(file_name, "r")
if character=='vowel':
brain_rat='aeiou'
elif character=='consonant':
brain_rat='bcdfghjklmnpqrstvwxyz'
elif character=='space':
brain_rat=''
else:
brain_rat='!@#$%^&*()_+=-123456789{}|":?><,./;[]\''
found=0
for line in in_file:
for i in range (len(brain_rat)):
found += finder(file_name,brain_rat[i+1,i+2])
in_file.close()
return found
def finder(file_name,character):
in_file = open(file_name, "r")
line_number = 1
found=0
for line in in_file:
line=line.lower()
found +=line.count(character)
return found
這似乎是你在finder_character
中嘗試做的finder_character
。 我不確定你為什么需要finder
。
在python中,你可以循環遍歷iterables(比如字符串),所以你不需要做range(len(string))
。
for line in in_file:
for i in brain_rat:
if i in line: found += 1
您的代碼中似乎還有一些其他奇怪之處:
line_number
從未使用過 這可能是一個更安全的版本, with open...
通常比open()... file.close()
更好,因為你不需要擔心錯誤處理和關閉。 我添加了一些評論來幫助解釋你想要做什么。
def finder_character(file_name,character):
found=0 # Initialise the counter
with open(file_name, "r") as in_file:
# Open the file
in_file = file_name.split('\n')
opts = { 'vowel':'aeiou',
'consonant':'bcdfghjklmnpqrstvwxyz',
'space':'' }
default= '!@#$%^&*()_+=-123456789{}|":?><,./;[]\''
for line in in_file:
# Iterate through each line in the file
for c in opts.get(character,default):
With each line, also iterate through the set of chars to check.
if c in line.lower():
# If the current character is in the line
found += 1 # iterate the counter.
return found # return the counter
如果要使用原始代碼,則必須將文件名傳遞給finder()
函數,並在那里打開文件,以查找要測試的每個字符。
原因是文件對象( in_file
)是生成器,而不是列表。 生成器的工作方式是,每次調用next()
方法時它都會返回下一個項目。 當你說
for line in in_file:
只要next()
方法“返回”(它實際上使用關鍵字yield
,但現在不考慮它in_file.next()
, for ... in
語句調用in_file.next()
)一個值。 當發電機不再返回任何值時,我們說發電機已耗盡。 您無法重復使用耗盡的發電機。 如果你想重新開始,你必須制作一個新的發電機。
我允許自己重寫你的代碼。 這應該會給你想要的結果。 如果有什么不清楚,請詢問!
def finder_character(file_name,character):
with open(file_name, "r") as ifile:
if character=='vowel':
brain_rat='aeiou'
elif character=='consonant':
brain_rat='bcdfghjklmnpqrstvwxyz'
elif character=='space':
brain_rat=' '
else:
brain_rat='!@#$%^&*()_+=-123456789{}|":?><,./;[]\''
return sum(1 if c.lower() in brain_rat else 0 for c in ifile.read())
的test.txt:
eeehhh
iii!#
kk ="k
oo o
輸出:
>>>print(finder_character('test.txt', 'vowel'))
9
>>>print(finder_character('test.txt', 'consonant'))
6
>>>print(finder_character('test.txt', 'space'))
2
>>>print(finder_character('test.txt', ''))
4
如果您在理解return
線時遇到問題,應該向后閱讀,如下所示:
Sum this generator:
Make a generator with values as v in:
for row in ifile.read():
if c.lower() in brain_rat:
v = 1
else:
v = 0
如果您想了解有關生成器的更多信息,我推薦有關它的Python Wiki頁面 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.