假设我有一段包含不同语言的段落。喜欢:
This is paragraph in English. 这是在英国段。Это пункт на английском языке. این بند در زبان انگلیسی است.
我想计算这个段落中包含英文单词的百分比(%)。所以想问问如何在 python 中做到这一点。
此离线解决方案使用 pyenchant 拼写检查模块:
# -*- coding: utf-8 -*
import enchant
dictionary = enchant.Dict("en_US")
paragraph = u"This is paragraph in English. 这是在英国段。Это пункт на английском языке. این بند در زبان انگلیسی است."
words = paragraph.split(" ")
en_count = 0.0
for word in words:
if dictionary.check(word.strip()):
en_count += 1
percent = en_count/len(words) if len(words) != 0 else 0
print str(percent) + "% english words"
输出:
31.25% english words
有贴发现段落有16个字。但是有吗?其中一个问题是,如果您想将英语单词的数量与句子中的单词数量进行比较,则很难仅使用英语语言方法。找到英语单词的数量“相对”容易,但第二部分,即找到句子中的总单词数,比较困难,因为你需要资源来消除“这是在英国段”中包含多少单词的歧义,为了找到英语单词占段落中单词的百分比。
尝试使用自然语言工具包。 NLTK 是一个 Python 库(正在与 Python3.0 兼容),它有内置函数来准确地满足您的需求(单词的出现频率、标记化字符串等),以及对英语语料库的访问如果您想通过将句子中的单词与语料库中包含的单词进行比较来查找英语单词,则可以使用将单词与 to 进行比较。
附带的书 Natural Language Processing with Python,Python 2.x 1 版可从 NLTK 网站免费在线获取。它作为对 NLTK 库和 Python 编程的总体介绍。 The Wordlist Corpus 或 Roget's Thesaurus Corpus 可能会有用。还有检测语言文本的。对于混合语言的情况,不确定那将如何工作。
首先,获取英文单词列表。然后,遍历文件并计数!
import string
import urllib2
punctuation = set(string.punctuation)
eng_words_url = 'https://raw.github.com/eneko/data-repository/master/data/words.txt'
eng_words = urllib2.urlopen(eng_words_url).readlines()
eng_words = [w.strip().lower() for w in eng_words]
def remove_punc(str):
return ''.join(c for c in str if c not in punctuation)
total_count = 0
eng_count = 0
with open('filename.txt') as f:
for line in f:
words = remove_punc(line).lower().split()
total_count += len(words)
eng_count += sum(1 for word in words if word.lower() in eng_words)
print '%s English words found' % eng_count
print '%s total words found' % total_count
percentage_eng = 0 if total_count == 0 else (float(eng_count) / total_count * 100)
print '%s%% of words were English' % percentage_eng
例如,这是您的示例文本:
这是英文段落。这是在英国段。Это пункт на английском языке。 اون بند در òبان انگلیسو است.
当我在上面运行上面的代码时,输出是这样的:
找到5个英文单词
总共找到 16 个词
31.25%的单词是英文
正如评论中指出的那样,由于中文单词之间没有空格,百分比不正确。总共有 22 个单词,所以百分比应该是 22.7%。
如果你用拉丁字母写的所有单词都是英文,你可以使用正则表达式。
做这种事情的一个有用的数据结构是trie
如果我们在other post:
中使用我的英语单词列表的分支import os
import json
import urllib3
eng_trie = {}
def add_to_trie(trie: dict, word: str, lower: bool=False) -> dict:
if lower:
word = word.lower()
letter = word[:1]
if len(word) == 1:
# This is the last letter, add a terminator
trie[word] = {**trie.get(word, {}), "EOW": True}
else:
if not trie.get(letter):
trie[letter] = {}
trie[letter] = add_to_trie(trie[letter], word[1:])
return trie
if __name__ == "__main__":
output_file = "./data/words.json"
url = "https://github.com/JonathanRys/data-repository/blob/master/data/words.txt?raw=true"
response = urllib3.request("GET", url)
if response.status:
for word in [word.strip() for word in response.data.decode().split('\n')]:
if word:
try:
add_to_trie(eng_trie, word, lower=True)
except Exception as e:
print(f'ERROR for word "{word}": {e}')
with open(output_file, 'w') as f:
print(json.dumps(eng_trie), file=f)
然后使用它
import json
json_trie = './data/words.json'
def get_data(file: str) -> dict:
with open(file) as f:
trie = json.loads(f.read())
return trie
def check(word: str, trie: dict=get_data(json_trie)) -> bool:
if len(word) == 1:
if trie.get(word):
if trie.get(word).get('EOW'):
return True
else:
return False
if trie:
next_trie = trie.get(word[:1])
if next_trie:
return check(word[1:], next_trie)
return False
def is_english(word: str) -> bool:
if not word:
return False
return check(word)
if __name__ == "__main__":
words = ['albatross', 'run', 'winner', 'success', 'erwrtwaf', 'albat']
for word in words:
if is_english(word):
print(f'English: {word}')
else:
print(f'Not English: {word}')