练习题:
1、打开中文字符的文档时,会出现乱码,Python自带的打开文件是否可以指定文字编码?还是只能用相关函数?
- linux使用’utf-8’编码方式,window使用’GBK’编码方式。
- linux平台编码(UTF-8)与window平台(GBK)不一样。
- 可以使用open(encoding=xx)进行转码
2、编写程序查找最长的单词
输入文档: res/test.txt
题目说明:
"""
Input file
test.txt
Output file
['general-purpose,', 'object-oriented,']
"""
def longest_word(filename):
# your code here
pass
import os
def longest_word(filename):
file = open(filename)
words = file.readlines()
file.close()
for i in range(len(words)-1):
words[i] = words[i][:-2]
max_str = []
for i in range(len(words)):
if [len == max(len_list) for len in len_list][i]:
max_str.append(words[i])
return max_str
longest_word('test.txt')
# ['general-purpose', 'object-oriented']