处理一些读取csv文件并获取用户查找的搜索词计数的代码。这个函数不应该区分大小写,因此如果用户想找到单词:trampoline,它会捕获trampoline、trampoline等
我想知道是否可以在同一个参数中添加.isupper()和.islower(),以简化代码?我感觉到我在做别的错事,只是很难找出那是什么。你知道吗
例如,从.csv文件
I have 12 trampolines. The TRAMPOLINES are round and have netting
surrounding them.
Trampolines are my favorite activity.
我尝试在单独的代码行中添加这两个方法,但遇到了意外的输出。你知道吗
def countingWords(word):
openFile= open('file.csv', 'r')
contents = openFile.read()
openFile.close
counter = 0
for separateLines in contents.split():
if str(word) in separateLines:
counter += 1
elif str(word).isupper():
counter += 1
elif str(word).islower():
counter += 1
return count
当前,如果用户输入:countingWords('Trampoline'),则输出将仅为1,而应为3
也许这太过分了,但你可以用正则表达式。为什么?它可能比分裂和循环快一点(并不是说它不会在幕后发生)。享受-我写了一个小片段下面!你知道吗
下面是一个答案,它使用列表理解来获得你的示例文本中单词的频率。你知道吗
另外,可以修改此代码以使用CSV文件。你知道吗
将目标词和文本行从文件转换为小写:
相关问题 更多 >
编程相关推荐