【发布时间】:2024-01-24 05:22:02
【问题描述】:
我想做的是将小说网站上的字符串组合在一起。帖子的标题通常采用以下格式:
titles = ['Series Name: Part 1 - This is the chapter name',
'[OC] Series Name - Part 2 - Another name with the word chapter and extra oc at the start',
"[OC] Series Name = part 3 = punctuation could be not matching, so we can't always trust common substrings",
'{OC} Another cool story - Part I - This is the chapter name',
'{OC} another cool story: part II: another post title',
'{OC} another cool story part III but the author forgot delimiters',
"this is a one-off story, so it doesn't have any friends"]
分隔符等并不总是存在,并且可能会有一些变化。
我首先将字符串规范化为字母数字字符。
import re
from pprint import pprint as pp
titles = [] # from above
normalized = []
for title in titles:
title = re.sub(r'\bOC\b', '', title)
title = re.sub(r'[^a-zA-Z0-9\']+', ' ', title)
title = title.strip()
normalized.append(title)
pp(normalized)
给了
['Series Name Part 1 This is the chapter name',
'Series Name Part 2 Another name with the word chapter and extra oc at the start',
"Series Name part 3 punctuation could be not matching so we can't always trust common substrings",
'Another cool story Part I This is the chapter name',
'another cool story part II another post title',
'another cool story part III but the author forgot delimiters',
"this is a one off story so it doesn't have any friends"]
我希望的输出是:
['Series Name',
'Another cool story',
"this is a one-off story, so it doesn't have any friends"] # last element optional
我知道比较字符串的几种不同方法...
difflib.SequenceMatcher.ratio()
我还听说过 Jaro-Winkler 和 FuzzyWuzzy。
但真正重要的是我们可以得到一个数字来显示字符串之间的相似性。
我想我需要想出(大部分)一个 2D 矩阵来比较每个字符串。但是一旦我知道了,我就无法思考如何将它们实际分成组。
我发现another post 似乎已经完成了第一部分......但我不知道如何从那里继续。
scipy.cluster 起初看起来很有希望……但后来我就想不通了。
另一个想法是以某种方式将itertools.combinations() 与functools.reduce() 与上述距离指标之一结合起来。
我是不是想太多了?看起来这应该很简单,但在我的脑海中没有任何意义。
【问题讨论】:
-
如果您想查看两个基于文本的对象有多相似,使用 Levenshtein 编辑距离或 SimHash 的方法可能对您有用。我对您想加入的内容有点困惑(如果您可以提供手动示例)。
-
如果您在大小写或标点符号方面遇到问题,您可以将所有内容转为小写并删除所有标点符号。
-
我的例子可能不够清楚。我正在解析数千个标题,标点符号的变化可能比我上面的小例子要大得多。我确实喜欢规范化字符串的建议(我可能会将所有内容删除/替换为所有小写字母数字标题),但这仍然留下了一旦我有一组规范化字符串的问题,我如何提取系列以及什么标题在每个
-
您正在尝试加入相似的标题,同时从最终结果中删除冗余信息?
标签: python python-3.x grouping cluster-analysis