URL로 파일을 가져와이 파일에서 가장 많은 단어를 가진 문자열을 반환해야합니다. 여기 내 코드입니다 :Python. URL로 파일을 읽을 때 파일 인코딩
from urllib.request import urlopen
def wordiest_line(url):
data = urlopen(url)
if data:
max_words = 0
max_line = ""
for line in data.readlines():
#print(line)
the_encoding = "utf-8"
line = line.decode(the_encoding)
line = line.rstrip()
line_words = line.split()
if len(line_words) > max_words:
max_words = len(line_words)
max_line = line
#print("%s to RETURN\n" % max_line)
return max_line
else:
return None
는 그리고이이 기능을 테스트하기 위해 주어진 일부 URL은 다음과 같습니다
- "http://math-info.hse.ru/f/2017-18/dj-prog/lines1.txt"
- ""
- "http://math-info.hse.ru/f/2017-18/dj-prog/lines2.txt"
을 링크 1과 3의 경우 제대로 작동합니다. 하지만 파일 인코딩으로 인해 wordiest_line("http://lib.ru/FOUNDATION/3laws.txt_Ascii.txt")
이 제대로 작동하지 않으므로 키릴 문자로 된 텍스트가 있습니다.
문자열 인코딩을 정의하고 디코딩하려고했습니다. 여기에 코드입니다 :
from urllib.request import urlopen
import chardet
def wordiest_line(url):
data = urlopen(url)
if data:
max_words = 0
max_line = ""
for line in data.readlines():
#print(line)
the_encoding = chardet.detect(line)['encoding']
line = line.decode(the_encoding)
#print(the_encoding, line)
line = line.rstrip()
line_words = line.split()
if len(line_words) > max_words:
max_words = len(line_words)
max_line = line
#print("%s to RETURN\n" % max_line)
return max_line
else:
return None
그리고 지금 wordiest_line("http://lib.ru/FOUNDATION/3laws.txt_Ascii.txt")
오류와 함께 실패 '문자표'코덱의 위치는 8 바이트 0xdc를 디코딩 할 수 없습니다 문자는 아직 정의되지 않은
다른 URL로 매핑 잘 작동합니다. 그것을 고칠 수있는 제안이 있습니까?