我創建了一個函數來計算字母e,例如字母e。我的功能類似於這樣的東西:TypeError:在調用函數時,必須是str,而不是Python 3中的列表
def count_letter(sentence, accents, case):
lower_case_e = ['e']
upper_case_E = ['E']
accent_lower_case = ['é', 'ê', 'è']
accent_upper_case = ['É', 'Ê', 'È']
for character in sentence:#If statement for optional argument where ignore_accents == True and ignore_case == False.
#This loop will count lower case and upper case e as differente letters but will treat accented characters the same.
if accents == True and case == False:
lower_case_count = sentence.count(lower_case_e)
accent_lower_case_count = sentence.count(accent_lower_case)
upper_case_count = sentence.count(upper_case_E)
accent_upper_case_count = sentence.count(accent_upper_case)
total_e_count = lower_case_count + accent_lower_case_count
total_E_count = upper_case_count + accent_upper_case_count
return {'Total number of lower case e in sentence ignoring accents':total_e_count, 'Total number of upper case E in sentence ignoring accents':total_E_count }
此功能的點來算字母E,並根據它是否是大寫或小寫,或者如果它有口音,以字母加在一起。我創建一個文本文件名爲sentence.txt,它看起來像這樣:
Testing if function can count letter e or E.
我曾嘗試使用下面的代碼讀取文件:
# Reading the data from sentence.txt as a string
with open('sentence.txt', 'r') as Sentence_file:
Sentence_string=Sentence_file.read().replace('\n', '')
和讀取文件後,我試圖調用該函數以下列方式:
count_letter(sentence, True, False)
然而,當我嘗試運行此我得到以下錯誤:
TypeError: must be str, not list
任何人有任何想法可能會出錯?錯誤可能是我正在閱讀我的txt.file的方式嗎?任何建議將不勝感激!
完全錯誤跟蹤看起來是這樣的:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-b171590ddd67> in <module>()
29 with open('Test_Sentence1.txt', 'r') as Sentence1_file:
30 Sentence1=Sentence1_file.read().replace('\n', '')
---> 31 count_letter_e(Sentence1, True, False)
32
<ipython-input-2-b171590ddd67> in count_letter_e(sentence, accents, case)
18 if accents == True and case == False:#If statement for optional argument where ignore_accents == True and ignore_case == False.
19 #This loop will count lower case and upper case e as differente letters but will treat accented characters the same.
---> 20 lower_case_count = sentence.count(lower_case_e)#counting lower case e with no accent from the sentence
21 accent_lower_case_count = sentence.count(accent_lower_case)#counting lower case e with accents from the sentence
22 upper_case_count = sentence.count(upper_case_E)#counting upper case E with no accent from the sentence
TypeError: must be str, not list
跟蹤有什麼確切的錯誤? – Carcigenicate
這是一個你正在尋找幫助的作業問題嗎? – pcurry
該功能肯定是錯誤的。要麼你無用地遍歷你的'for'循環多少次,因爲你的句子中有字符,最終返回'None',否則你只會執行'for'循環的一次迭代。 –