【发布时间】:2016-05-23 07:23:08
【问题描述】:
我有一个文本集合,其中包含完全用英语、印地语或马拉地语的句子,每个句子的 id 分别为 0、1、2,分别代表文本的语言。
无论任何语言的文本都可能带有 HTML 标记、标点符号等。
我可以使用下面的代码清理英文句子:
import HTMLParser
import re
from nltk.corpus import stopwords
from collections import Counter
import pickle
from string import punctuation
#creating html_parser object
html_parser = HTMLParser.HTMLParser()
cachedStopWords = set(stopwords.words("english"))
def cleanText(text,lang_id):
if lang_id == 0:
str1 = ''.join(text).decode('iso-8859-1')
else:
str1 = ''.join(text).encode('utf-8')
str1 = html_parser.unescape(str1)
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', str1)
#print "cleantext before puncts removed : " + cleantext
clean_puncts = re.compile(r'[\s{}]+'.format(re.escape(punctuation)))
cleantext = re.sub(clean_puncts,' ',cleantext)
#print " cleantext after puncts removed : " + cleantext
cleanest = cleantext.lower()
if lang_id == 0:
cleanertext = ' '.join([word for word in cleanest.split() if word not in cachedStopWords])
words = re.findall(r"[\w']+", cleanertext)
words_final = [x.encode('UTF8') for x in words]
else:
words_final = cleanest.split()
return words_final
但它给了我以下印地语和马拉地语文本的错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xeb in position 104: ordinal not in range(128)
此外,它会删除所有单词。
印地语文本就像
<p>भारत का इतिहास काफी समृद्ध एवं विस्तृत है। </p>
我怎样才能对印地语或马拉地语文本做同样的事情?
【问题讨论】:
-
你能把文字贴在网上吗?
-
不同
line and parts of line。在编码之前准备语言字符串。拳头unicode稍后str。 -
python2或python3? -
@alvas : python 2.7
-
你能显示完整的代码吗?答案很大程度上取决于您阅读文件的方式。
标签: python python-2.7 unicode nltk