如何在一行代码中包含.isupper()和.islower()方法?

2024-09-29 00:13:36 发布

您现在位置:Python中文网/ 问答频道 /正文

处理一些读取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


Tags: 文件csv代码用户havecountercontentsare
3条回答

也许这太过分了,但你可以用正则表达式。为什么?它可能比分裂和循环快一点(并不是说它不会在幕后发生)。享受-我写了一个小片段下面!你知道吗

import re

data = """
I have 12 trampolines. The TRAMPOLINES are round and have netting 
surrounding them.

Trampolines are my favorite activity.
"""

def count_instances(data, word):
    res = re.findall('.?{}.?'.format(word.lower()), data, flags=re.IGNORECASE)
    print(res)
    return len(res)


print(count_instances(data, 'trampolines'))

下面是一个答案,它使用列表理解来获得你的示例文本中单词的频率。你知道吗

另外,可以修改此代码以使用CSV文件。你知道吗

from pprint import pprint

input_text = """
I have 12 trampolines. The TRAMPOLINES are round and have netting 
surrounding them.

Trampolines are my favorite activity.
"""

wordfreq = Counter([word.lower().rstrip('.') for word in input_text.split()])

pprint (wordfreq)
# outputs 
Counter({'trampolines': 3,
     'have': 2,
     'are': 2,
     'i': 1,
     '12': 1,
     'the': 1,
     'round': 1,
     'and': 1,
     'netting': 1,
     'surrounding': 1,
     'them': 1,
     'my': 1,
     'favorite': 1,
     'activity': 1})

将目标词和文本行从文件转换为小写:

for separateLines in contents.split():
    if word.lower() in separateLines.lower():
        counter += 1

相关问题 更多 >