使用 Python 检测文件中的语言更改
Detect language changes in file using Python
我需要检测文件中的语言变化,并相应地标记每个单词。我想出了一个 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 等工具
由于很长时间没有发布其他答案,我接受稍微编辑过的初始脚本作为解决我问题的最佳方法。
在研究它时,另一种更好的方法是忽略错误 normalizing 首先。
我需要检测文件中的语言变化,并相应地标记每个单词。我想出了一个 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 等工具
由于很长时间没有发布其他答案,我接受稍微编辑过的初始脚本作为解决我问题的最佳方法。
在研究它时,另一种更好的方法是忽略错误 normalizing 首先。