如何计算文件中某行中某个单词的出现次数?

问题描述 投票:0回答:1

我有以下问题。在我的Python初学者课程中,期中考试即将来临,虽然我了解期中实践中的其余问题,但这一点让我有些困惑。首先,这是问题的内容。我遇到麻烦的地方是想出如何遍历一行中的每个单词并检查是否已经看到它。我发现很难概念化。首先,这是问题的文本:

编写一个具有两个参数的名为cloneLines的函数:1. inFile,一个字符串,是调用cloneLines之前存在的输入文件的名称2. outFile,一个字符串,cloneLines创建并写入其中的输出文件的名称

函数cloneLines逐行读取inFile的内容,并将包含至少一个单词的任何行写入outFile,该单词在该行上多次出现。您可以假定输入文件仅包含小写字母,空格和换行符。

例如,如果以下是文件william.txt的内容:

double double toil and trouble
fire burn and caldron bubble
eye of newt and toe of frog
fillet of a fenny snake
in the caldron boil and bake
double double toil and trouble
fire burn and caldron bubble

以下函数调用:

inFile = 'william.txt'
outFile = 'clones.txt'
cloneLines(inFile, outFile)

应创建包含内容的文件clones.txt

double double toil and trouble
eye of newt and toe of frog
double double toil and trouble

我只是打开文件进行读写,并开始for循环。同样,我在掌握这一点时遇到了麻烦。任何其他阅读建议都将非常有帮助。我应该拆分从文件读取的行吗?我只需要指出一个大致的方向。

def cloneLines (inFile, outFile):
    inputfile = open(infile)
    outputfile = open(outfile, 'w')

    for line in inputfile.read():
        ...
python file writing
1个回答
0
投票

以下内容将在同一行中多次包含相同单词的任何行写入输出文件。

import sys

class SplitStream:
    """
    This is just so you can see the contents
    of the output file
    without having to open the output file
    """
    def __init__(self, s1, s2):
        self.s1 = s1
        self.s2 = s2
    def write(self, arg):
        self.s1.write(arg)
        self.s2.write(arg)


def cloneLines(inFile:str, outFile:str):
    inFile  = str(inFile)
    outFile = str(outFile)
    with open(inFile , mode = "r") as i_f:
        with open(outFile, mode="w") as o_f:
            o_f = SplitStream(o_f, sys.stdout)
            # TODO remove `SplitStream`
            for line in i_f:
                if contains_a_word_more_than_once(line):
                    o_f.write(line)

def contains_a_word_more_than_once(stryng):
    stryng = str(stryng)
    sep_words = stryng.split(" ")

    # if `stryng` is...
    #     "fillet of a fenny snake"
    #
    # then `sep_words` is:
    #     ["fillet", "of", "a", "fenny", "snake"]

    d = dict()    
    for word in sep_words:
        if word in d.keys():
            return True
        d[word] = True
    return False
© www.soinside.com 2019 - 2024. All rights reserved.