gpt4 book ai didi

python - 如何有效统计字符串别名?

转载 作者:行者123 更新时间:2023-11-30 22:14:24 25 4
gpt4 key购买 nike

我正在开发一个个人项目,该项目对文本中提到的名称实例进行计数。我知道我可以使用collections.Counter()来做到这一点,但我不确定如何有效地考虑别名。

例如,假设我想要计算的名字之一是“Tim”,但我也想计算他拥有的任何昵称,例如“Timmy”“蒂姆斯特”

我有一些字符串说,“哦蒂姆要去参加聚会吗?”“是的,我的 child 蒂米,不会错过它,他喜欢聚会!”, “哇哦,Timster 本人要走了?算我一个!”

我希望将其全部计为 “Tim” 这样的变量。我知道我可以简单地单独计算它们,然后将计数加在一起。但我觉得有更好的方法可以做到这一点。

即我希望我的代码看起来更像。

names = {
'Tim':{'Tim', 'Timmy', 'Timster'},
... other names here.}
# add any occurrence of Tim names to Tim and other occurrences of other names to their main name.

与类似的东西相反

total_tim = Counter(tim) + Counter(timmy) + Counter(timster), etc..

对于每个名称。有谁知道我该怎么做?

最佳答案

from collections import Counter

TEXT = '''
Blah Tim blah blah Timmy blah Timster blah Tim
Blah Bill blah blah William blah Billy blah Bill Bill
'''
words = TEXT.split()

# Base names a their aliases.
ALIASES = dict(
Tim = {'Tim', 'Timmy', 'Timster'},
Bill = {'Bill', 'William', 'Billy'},
)

# Given any name, find its base name.
BASE_NAMES = {a : nm for nm, aliases in ALIASES.items() for a in aliases}

# All names.
ALL_NAMES = set(nm for aliases in ALIASES.values() for nm in aliases)

# Count up all names.
detailed_tallies = Counter(w for w in words if w in ALL_NAMES)

# Then build the summary counts from those details.
summary_tallies = Counter()
for nm, n in detailed_tallies.items():
summary_tallies[BASE_NAMES[nm]] += n

print(detailed_tallies)
print(summary_tallies)

# Counter({'Bill': 3, 'Tim': 2, 'Timmy': 1, 'Timster': 1, 'William': 1, 'Billy': 1})
# Counter({'Bill': 5, 'Tim': 4})

关于python - 如何有效统计字符串别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50538330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com