Python输入输出文件

2024-04-25 21:58:57 发布

您现在位置:Python中文网/ 问答频道 /正文

遇到问题(为即将到来的考试做复习)。第一个问题要求我将每行文本中的字数打印到输出文件中。这是一项容易的任务(我将提供我使用的代码)。另一个类似的问题是,打印出每行文本中唯一单词的数量。我所能得到的最远的结果是在列表中添加单词,然后打印列表的长度。。。但它最终将每个迭代相加。所以它会打印7,14,21,而不是7,7,7(只是一个帮助exapain的例子),我该如何着手修复这个代码以使其正常工作?我已经试了30分钟了。任何帮助都将不胜感激

每行字数代码:

def uniqueWords(inFile,outFile):
    inf = open(inFile,'r')
    outf = open(outFile,'w')
    for line in inf:
        wordlst = line.split()
        count = len(wordlst)
        outf.write(str(count)+'\n')

    inf.close()
    outf.close()
uniqueWords('turn.txt','turnout.txt')

每行中唯一字数的代码(失败):

def uniqueWords(inFile,outFile):
    inf = open(inFile,'r')
    outf = open(outFile,'w')
    unique = []
    for line in inf:
        wordlst = line.split()
        for word in wordlst:
            if word not in unique:
                unique.append(word)
        outf.write(str(len(unique)))

    inf.close()
    outf.close()
uniqueWords('turn.txt','turnout.txt')

Tags: 代码intxtforcloselineopeninfile
1条回答
网友
1楼 · 发布于 2024-04-25 21:58:57

如果第一个有效,请尝试set

def uniqueWords(inFile,outFile):
    inf = open(inFile,'r')
    outf = open(outFile,'w')
    for line in inf:
        wordlst = line.split()
        count = len(set(wordlst))
        outf.write(str(count)+'\n')

    inf.close()
    outf.close()
uniqueWords('turn.txt','turnout.txt')

相关问题 更多 >