3

我需要检测文件中的语言变化,并相应地标记每个单词。我想出了一个 hacky 方式,适用于 2 种语言(英语和希腊语)。

脚本是这样的:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

#open file
filename = sys.argv[1]
f = open(filename,'r')
content = f.read()
f.close()


#initialize new content
newSentence=''
#for every line, if the first letter of the token isn't ascii, it's nonsense, tag it.
for line in content.split('\n'):
    newSentence+='\n'
    for token in line.split():
        try:
            result = token[0].decode('ascii','ignore')
            newSentence += ' /en'+token
        except:
            newSentence += ' /gr'+token


print newSentence

f=open(filename+'_new.txt','w')
f.write(newSentence)
f.close()

主要思想是,如果每个单词的第一个字母不是 ascii 可解码的,它就不能是英文,所以它是唯一的其他选择。

现在我意识到这非常hacky,我想知道我将如何以更pythonic的方式去做?甚至以一种适用于文档中多种语言的方式。

PS。我通常知道如何检测文档中的语言,但是我想知道是否有更快的方法来检测更改而不调用 nltk 等工具。

4

1 回答 1

0

由于很长一段时间没有发布其他答案,我接受稍微编辑的初始脚本作为解决我问题的最佳方法。

在研究另一种更好的方法时,忽略错误将首先正常化

于 2016-12-17T20:02:00.360 回答