【问题标题】:Group strings with values in Python在 Python 中使用值对字符串进行分组
【发布时间】:2019-03-07 22:24:07
【问题描述】:

我正在处理 twitter 主题标签,我已经计算过它们出现在我的 csv 文件中的次数。我的 csv 文件如下所示:

GilletsJaunes, 100
Macron, 50
gilletsjaune, 20
tax, 10

现在,我想使用fuzzywuzzy 库将两个相近的术语组合在一起,例如“GilletsJaunes”和“gilletsjaune”。如果 2 个术语之间的接近度大于 80,则它们的值仅添加到 2 个术语中的一个中,而另一个则被删除。这将给出:

GilletsJaunes, 120
Macron, 50
tax, 10

使用“fuzzywuzzy”:

from fuzzywuzzy import fuzz
from fuzzywuzzy import process

fuzz.ratio("GiletsJaunes", "giletsjaune")
82 #output

【问题讨论】:

  • 到目前为止你尝试过什么?请展示您的尝试,以便我们帮助您更正。

标签: python grouping levenshtein-distance fuzzywuzzy


【解决方案1】:

首先,复制 these two functions 以便能够计算 argmax:

# given an iterable of pairs return the key corresponding to the greatest value
def argmax(pairs):
    return max(pairs, key=lambda x: x[1])[0]


# given an iterable of values return the index of the greatest value
def argmax_index(values):
    return argmax(enumerate(values))

其次,将 CSV 的内容加载到 Python 字典中,然后执行以下操作:

from fuzzywuzzy import fuzz

input = {
    'GilletsJaunes': 100,
    'Macron': 50,
    'gilletsjaune': 20,
    'tax': 10,
}

threshold = 50

output = dict()
for query in input:
    references = list(output.keys()) # important: this is output.keys(), not input.keys()!
    scores = [fuzz.ratio(query, ref) for ref in references]
    if any(s > threshold for s in scores):
        best_reference = references[argmax_index(scores)]
        output[best_reference] += input[query]
    else:
        output[query] = input[query]

print(output)

{'GilletsJaunes': 120, 'Macron': 50, '税': 10}

【讨论】:

    【解决方案2】:

    这解决了您的问题。您可以通过首先将标签转换为小写来减少输入样本。我不确定fuzzywuzzy 是如何工作的,但我怀疑“HeLlO”和“hello”和“HELLO”总是大于80,它们代表同一个词。

    import csv
    from fuzzywuzzy import fuzz
    
    data = dict()
    output = dict()
    tags = list()
    
    with open('file.csv') as csvDataFile:
        csvReader = csv.reader(csvDataFile)
        for row in csvReader:
            data[row[0]] = row[1]
            tags.append(row[0])
    
    for tag in tags:
        output[tag] = 0
        for key in data.keys():
            if fuzz.ratio(tag, key) > 80:
                output[tag] = output[tag] + data[key]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 2013-08-13
      • 2017-09-25
      • 1970-01-01
      相关资源
      最近更新 更多