UnicodeDecodeError : 'ascii'코덱이 위치 13에서 바이트 0xe2를 디코딩 할 수 없습니다.
NLTK를 사용하여 각 줄이 문서로 간주되는 텍스트 파일에서 kmeans 클러스터링을 수행하고 있습니다. 예를 들어 내 텍스트 파일은 다음과 같습니다.
belong finger death punch <br>
hasty <br>
mike hasty walls jericho <br>
jägermeister rules <br>
rules bands follow performing jägermeister stage <br>
approach
이제 실행하려는 데모 코드는 다음과 같습니다.
import sys
import numpy
from nltk.cluster import KMeansClusterer, GAAClusterer, euclidean_distance
import nltk.corpus
from nltk import decorators
import nltk.stem
stemmer_func = nltk.stem.EnglishStemmer().stem
stopwords = set(nltk.corpus.stopwords.words('english'))
@decorators.memoize
def normalize_word(word):
return stemmer_func(word.lower())
def get_words(titles):
words = set()
for title in job_titles:
for word in title.split():
words.add(normalize_word(word))
return list(words)
@decorators.memoize
def vectorspaced(title):
title_components = [normalize_word(word) for word in title.split()]
return numpy.array([
word in title_components and not word in stopwords
for word in words], numpy.short)
if __name__ == '__main__':
filename = 'example.txt'
if len(sys.argv) == 2:
filename = sys.argv[1]
with open(filename) as title_file:
job_titles = [line.strip() for line in title_file.readlines()]
words = get_words(job_titles)
# cluster = KMeansClusterer(5, euclidean_distance)
cluster = GAAClusterer(5)
cluster.cluster([vectorspaced(title) for title in job_titles if title])
# NOTE: This is inefficient, cluster.classify should really just be
# called when you are classifying previously unseen examples!
classified_examples = [
cluster.classify(vectorspaced(title)) for title in job_titles
]
for cluster_id, title in sorted(zip(classified_examples, job_titles)):
print cluster_id, title
내가받는 오류는 다음과 같습니다.
Traceback (most recent call last):
File "cluster_example.py", line 40, in
words = get_words(job_titles)
File "cluster_example.py", line 20, in get_words
words.add(normalize_word(word))
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/nltk/decorators.py", line 183, in memoize
result = func(*args)
File "cluster_example.py", line 14, in normalize_word
return stemmer_func(word.lower())
File "/usr/local/lib/python2.7/dist-packages/nltk/stem/snowball.py", line 694, in stem
word = (word.replace(u"\u2019", u"\x27")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 13: ordinal not in range(128)
여기서 무슨 일이 일어나고 있습니까?
파일이 str
s 로 읽혀지고 있지만 unicode
s 여야합니다 . 파이썬은 암시 적으로 변환하려고하지만 실패합니다. 변화:
job_titles = [line.strip() for line in title_file.readlines()]
str
s 를 명시 적으로 디코딩하려면 unicode
(여기서는 UTF-8이라고 가정) :
job_titles = [line.decode('utf-8').strip() for line in title_file.readlines()]
또한 수입에 의해 해결 될 수 모듈 및 사용하여 내장보다는 .codecs
codecs.open
open
이것은 나를 위해 잘 작동합니다.
f = open(file_path, 'r+', encoding="utf-8")
You can add a third parameter encoding to ensure the encoding type is 'utf-8'
Note: this method works fine in Python3, I did not try it in Python2.7.
You can try this also:
import sys
reload(sys)
sys.setdefaultencoding('utf8')
For me there was a problem with the terminal encoding. Adding UTF-8 to .bashrc solved the problem:
export LC_CTYPE=en_US.UTF-8
Don't forget to reload .bashrc afterwards:
source ~/.bashrc
When on Ubuntu 18.04 using Python3.6 I have solved the problem doing both:
with open(filename, encoding="utf-8") as lines:
and if you are running the tool as command line:
export LC_ALL=C.UTF-8
Note that if you are in Python2.7 you have do to handle this differently. First you have to set the default encoding:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
and then to load the file you must use io.open
to set the encoding:
import io
with io.open(filename, 'r', encoding='utf-8') as lines:
You still need to export the env
export LC_ALL=C.UTF-8
To find ANY and ALL unicode error related... Using the following command:
grep -r -P '[^\x00-\x7f]' /etc/apache2 /etc/letsencrypt /etc/nginx
Found mine in
/etc/letsencrypt/options-ssl-nginx.conf: # The following CSP directives don't use default-src as
Using shed
, I found the offending sequence. It turned out to be an editor mistake.
00008099: C2 194 302 11000010
00008100: A0 160 240 10100000
00008101: d 64 100 144 01100100
00008102: e 65 101 145 01100101
00008103: f 66 102 146 01100110
00008104: a 61 097 141 01100001
00008105: u 75 117 165 01110101
00008106: l 6C 108 154 01101100
00008107: t 74 116 164 01110100
00008108: - 2D 045 055 00101101
00008109: s 73 115 163 01110011
00008110: r 72 114 162 01110010
00008111: c 63 099 143 01100011
00008112: C2 194 302 11000010
00008113: A0 160 240 10100000
You can try this before using job_titles
string:
source = unicode(job_titles, 'utf-8')
For python 3, the default encoding would be "utf-8". Following steps are suggested in the base documentation:https://docs.python.org/2/library/csv.html#csv-examples in case of any problem
Create a function
def utf_8_encoder(unicode_csv_data): for line in unicode_csv_data: yield line.encode('utf-8')
Then use the function inside the reader, for e.g.
csv_reader = csv.reader(utf_8_encoder(unicode_csv_data))
python3x or higher
load file in byte stream:
body = '' for lines in open('website/index.html','rb'): decodedLine = lines.decode('utf-8') body = body+decodedLine.strip() return body
use global setting:
import io import sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')
Use open(fn, 'rb').read().decode('utf-8')
instead of just open(fn).read()
'Programming' 카테고리의 다른 글
특정 주석이있는 클래스의 모든 메소드에 대한 @AspectJ pointcut (0) | 2020.07.21 |
---|---|
getApplication (), getApplicationContext (), getBaseContext () 및 someClass.this를 사용할 때의 차이점 (0) | 2020.07.21 |
Netbeans 8.2에서 프로젝트를 작성할 수 없습니다 (0) | 2020.07.21 |
자신 만의 STL 컨테이너 작성 (0) | 2020.07.21 |
앞에 0이있는 Javascript parseInt () (0) | 2020.07.21 |