【发布时间】:2014-02-23 04:58:16
【问题描述】:
我尝试在希腊文本中使用 NLTK pagkage,但我处理了一个很大的编码问题。我的代码在下面
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, string, re, nltk
def find_bigrams(input_list):
bigram_list = []
for i in range(len(input_list)-1):
bigram_list.append((input_list[i], input_list[i+1]))
return bigram_list
def get_nice_string(list_or_iterator):
return "[" + " , ".join( str(x) for x in list_or_iterator) + "]"
def stripText(rawText):
text = rawText
rules = [
{r'{[^)]*\}' : ''}, # remove curly brackets
{r'\([^)]*\)' : ''}, # remove parentheses
{r'^https?:\/\/.*[\r\n]*' : ''},# remove urls
{r' +' : ' '}, # remove multiple whitespaces
{r'^\s+': ''}, # remove whitespaces beginning
{r'\.\.+' : '.'} # remove multiple fullstops
]
for rule in rules:
for (k, v) in rule.items():
regex = re.compile(k)
text = regex.sub(v, text)
sentenceClean = text.translate(string.maketrans('', ''), '{}[]|?"=\'')
return sentenceClean
if __name__ == '__main__':
f = open('C:\\Users\\Dimitris\\Desktop\\1.txt', 'r').readlines()
newFile = open('C:\\Users\\Dimitris\\Desktop\\corpus.txt', 'w')
newFile1 = open('C:\\Users\\Dimitris\\Desktop\\words.txt', 'w')
words = ['jpg', 'jpeg', 'File', 'Image']
for line in f:
sentences = stripText(line)
whitespaces = sentences.count(' ')
if any(word in sentences for word in words):
continue
elif whitespaces < 20:
continue
else:
newFile.write(sentences+'\n')
b = nltk.word_tokenize(sentences)
print get_nice_string(b)
get_nice_string(nltk.bigrams(b))
print get_nice_string(nltk.bigrams(b))
newFile1.write(get_nice_string(b))
newFile.close()
newFile1.close()
当我尝试从 nltk.word_tokenize(sentences) 打印输出时,结果类似于 (('\xe5\xe3\xea\xfe\xec\xe9\xe1', '\xe3\xe9') ),但是如果我使用 get_nice_string() 函数并将列表转换为字符串,则结果是正常的希腊文本。 到目前为止,一切都很好。
但是无论我使用 find_bigrams() 函数还是 nltk.bigrams() 我都会得到类似上面的字符串 (('\xe5\xe3\xea\xfe\xec\xe9\xe1', '\xe3\xe9')) ,即使我使用 get_nice_string() 函数,为了将列表变成字符串。
另外,我尝试使用 codecs.open() 函数打开文件,像这样
f = codecs.open('C:\\Users\\Dimitris\\Desktop\\1.txt', 'r', 'utf-8').readlines()
但问题仍然存在。
有什么想法吗?
【问题讨论】:
标签: python python-2.7 encoding nlp nltk