我正在尝试浏览(主要是(阿拉伯语句子的列表,并删除那些不是阿拉伯语的句子。我有一个骇客,说明角色是否是阿拉伯语:阿拉伯语没有案例,因此,如果角色是alpha但不是上案或较低的情况,那是阿拉伯语。
我有以下代码,它有效,但是与其他过滤器相比,语言标识零件非常慢。在我看来,它在做任何特别复杂的事情,所以我不明白为什么要花这么长时间。(在过滤之前,语料库的大小约为300k句子。(
我可以做些什么来使其更有效?
谢谢!
def test_lang(string):
"""Takes a string and determines if it is written in Arabic
characters or foreign, by testing whether the first character
has a case attribute. This is intended for Arabic texts that
may have English or French words added. If it encounters another
case-less language (Chinese for instance), it will falsely
identify it as Arabic."""
if not string or not string.isalpha():
return None
char = string[0]
if char.isalpha() and not (char.islower() or char.isupper()):
lang = 'AR'
else:
lang = 'FW'
return lang
...
# remove sentences that are in English or French - THIS IS SLOW (takes a few mins)
for sent in sents:
if sent and test_lang(sent[0]) != 'AR':
sents.remove(sent)
# remove clearly MSA sentences -- THIS IS FAST (takes a few seconds)
msa_features = ['ليس','لست','ليست','ليسوا','الذي','الذين','التي','ماذا', 'عن']
p = re.compile('|'.join(msa_features))
for sent in sents:
if re.search(p, sent):
sents.remove(sent)
list.remove
为此目的非常慢 - 它每次搜索给定值的整个列表,然后删除它。它必须有效地遍及整个列表的每个元素,从而导致二次运行时。
更好的解决方案是以下列表表达式:
sents = [
sent for sent in sents
if test_lang(sent[0]) == 'AR' and not re.search(p, sent)
]
这以线性时间过滤列表。
(我猜第一个过滤器必须在很长的列表上操作并放弃其中的大部分?而第二个过滤器收到的列表要小得多,不必删除太多?这会解释为什么第一个一个慢得多。(