mno*_*tka 5 python string random nlp heuristics
单词示例:
随机字符串的示例:
当然,随机字符串实际上可能是某种语言中的单词,或者看起来像一个单词。但是基本上,一个人能够说出某种看起来“随机”的东西,基本上只是通过检查您是否能够说出它。
我试图通过计算熵来区分这两者,但这远非完美。您还有其他想法,可行的算法吗?
但是有一个重要的要求,我不能使用像这样的重量级库nltk或使用字典。基本上,我需要的是一些在大多数情况下都可以使用的简单快速的启发式方法。
我开发了一个名为Nostril的 Python 3 包,用于解决与 OP 提出的问题密切相关的问题:确定在源代码挖掘期间提取的文本字符串是否是类/函数/变量/等。标识符或随机乱码。它不使用字典,但确实包含一个相当大的 n-gram 频率表来支持其对文本字符串的概率评估。(我不确定这是否符合“词典”的条件。)该方法不检查发音,并且其专业化可能使其不适合一般单词/非单词检测;尽管如此,也许它对于OP或其他想要解决类似问题的人来说是有用的。
示例:以下代码,
from nostril import nonsense
real_test = ['bunchofwords', 'getint', 'xywinlist', 'ioFlXFndrInfo',
'DMEcalPreshowerDigis', 'httpredaksikatakamiwordpresscom']
junk_test = ['faiwtlwexu', 'asfgtqwafazfyiur', 'zxcvbnmlkjhgfdsaqwerty']
for s in real_test + junk_test:
print('{}: {}'.format(s, 'nonsense' if nonsense(s) else 'real'))
Run Code Online (Sandbox Code Playgroud)
将产生以下输出:
bunchofwords: real
getint: real
xywinlist: real
ioFlXFndrInfo: real
DMEcalPreshowerDigis: real
httpredaksikatakamiwordpresscom: real
faiwtlwexu: nonsense
asfgtqwafazfyiur: nonsense
zxcvbnmlkjhgfdsaqwerty: nonsense
Run Code Online (Sandbox Code Playgroud)
警告我不是自然语言专家
假设链接If You Can Raed Tihs, You Mut Be Raelly Smrat中提到的内容是真实的,一个简单的方法是
创建单词的 python 字典,键作为字典中单词的第一个和最后一个字符
words = defaultdict()
with open("your_dict.txt") as fin:
for word in fin:
words[word[0]+word[-1]].append(word)
Run Code Online (Sandbox Code Playgroud)现在,对于任何给定的单词,搜索字典(记住键是单词的第一个和最后一个字符)
for matches in words[needle[0] + needle[-1]]:
Run Code Online (Sandbox Code Playgroud)比较字典中的值和你的针中的字符是否匹配
for match in words[needle[0] + needle[-1]]:
if sorted(match) == sorted(needle):
print "Human Readable Word"
Run Code Online (Sandbox Code Playgroud)一种相对较慢的方法是使用difflib.get_close_matches(word,possibility[, n][, cutoff])