1、打开中文字符的文档时,会出现乱码,Python自带的打开文件是否可以指定文字编码?还是只能用相关函数?
可以 open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
encoding=‘utf8’
2、编写程序查找最长的单词
输入文档: res/test.txt
题目说明:
def longest_word(filename):
try:
with open(filename, 'r', encoding='UTF-8') as f:
l =[]
String = f.read().split(' ')
s = [[x , len(x)] for x in String]
s = sorted(s, key=lambda x: x[1], reverse= True)
for x in s:
if x[1] < s[0][1]:
break
l.append(x[0])
return l
except OSError as error:
print('出错啦!%s' % str(error))