如何隔离包含特定字符的特定单词?



所以我正在为我的EPQ创建一个分析机器人,计算特定标签使用的时间。我该如何检查其他单词的字符串中的一个单词是否包含#?

第一种方法可以使用in检查字符串是否有子字符串,并使用字典收集每个唯一单词的计数:

texts = ["it's friday! #TGIF", "My favorite day! #TGIF"]
counts = {}
for text in texts:
for word in text.split(" "):
if "#" not in word:
continue
if word not in counts:
counts[word] = 0
counts[word] += 1
print(counts)
# {'#TGIF': 2}

这可以进一步改进:

  • 使用str.casefold()对不同大小写的文本进行规范化
  • 使用正则表达式忽略某些字符,例如'#tgif!'应该解析为'#tgif'

您已经有了一个不错的答案,所以真正的问题在于您希望得到什么样的数据。下面是另一个解决方案,在相同的数据上使用Python的re模块:

import re
texts = ["it's friday! #TGIF #foo", "My favorite day! #TGIF"]
[re.findall('#(w+)', text) for text in texts]

正则表达式需要一些时间来适应。'#(w+)''捕获'(带括号)任何散列字符('#')之后的'word' (w+)。它会生成数据集中每个"文档"的标签列表:

[['TGIF', 'foo'], ['TGIF']]

那么你可以用这个技巧得到总数:

from collections import Counter
from itertools import chain
Counter(chain.from_iterable(finds))

产生类似字典的东西:

Counter({'TGIF': 2, 'foo': 1})
test = " if a word in a string of other words contains a #"
if "#" in test:
print("yes")