Python基础之文件与文件系统

文件与文件系统

练习题

1、打开中文字符的文档时,会出现乱码,Python自带的打开文件是否可以指定文字编码?还是只能用相关函数?
open(file, mode=‘r’, buffering=None, encoding=None, errors=None, newline=None, closefd=True)
在mode中设置文件打开的编码形式

2、编写程序查找最长的单词

输入文档: res/test.txt

题目说明:

"""
   
Input file
   test.txt
   
Output file
   ['general-purpose,', 'object-oriented,']
   
"""
def longest_word(filename):
    # your code here
        pass
   
def longest_word(filename):
    wenjian=open(filename,'r',encoding='UTF-8')
    lines=wenjian.readlines()
    #print(lines)
    #newlines=[wenjian.strip('\n')for line in wenjian.readlines()]
    #print(newlines)
    #longest=max(lines,key=len)
    changdu=0
    longest=[]
    for each in lines:
        each.strip()
        #print(each)
        a=len(each)
        #print(a)
        if a>=changdu:
            if a>changdu:
                longest=[]
                #a.strip()
                changdu=a
                longest.append(each.strip())
            #print(a,changdu,each,longest)
            elif a==changdu:
                longest.append(each.strip())
        else:
            continue
    '''print(lines)
    longest_list=max(lines)
    print(longest_list)'''
    '''for x in longest:
        #x1=x.strip('\n')
        #longest
        print(x)'''
    print(longest)
longest_word('test.txt')
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页