我创建了一个函数来计算一个字母,例如字母 e。我的函数看起来与此类似:
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
原文由 adda.fuentes 发布,翻译遵循 CC BY-SA 4.0 许可协议
“ count() ”函数只接受一个字符串作为输入。例如: