Python повторяющихся слов, записанных в outFile - где определить «я» - PullRequest
0 голосов
/ 09 апреля 2020

Я искренне извиняюсь, если это неправильный способ задать мой вопрос. Это мой первый пост в стеке.

Мой inFile - это шесть отредактированных строк стихотворения, которые не go нежны в ночи. Он должен распечатать outFile, который содержит строки, содержащие слово длиной более 3 букв, которое является дубликатом. В примере «ярость ярости против смерти света» будет напечатано из-за «ярости».

edit: Когда я запускаю это, я получаю сообщение об ошибке, в котором говорится, что «i» не определено.

О, и я не могу использовать никакие модули.

Вот мой код:

def duplicateWordLines(inFile,outFile):
    inFile=open(inFileName, "r")
    outFile=open(outFileName, "w")

    for line in inFile:
        words=line.split() #split the lines
        og=[] #orignal words
        dups=[] #duplicate words

        for word in words: #for each word in words
            if og.count(i)>0 and line not in dups: #if the word appears more than once and not already in duplicates
                dups.append(line) #add to duplicates
            else: #if not a duplicate 
                og.append(i) #add to the original list - not to worry about it

    for line in dups: #for the newly appended lines
        outFile.write(line+'\n') #write in the outFile 


#test case
inFileName="goodnightPoem.txt"
outFileName="goodnightPoemDUP.txt"

duplicateWordLines(inFileName,outFileName)

#should print 
#rage rage against the dying of the light
#do not go gentle into that good good night

Спасибо!

1 Ответ

0 голосов
/ 09 апреля 2020

Попробуйте это ...


def duplicateWordLines(inFile,outFile):
    inFile=open(inFileName, "r")
    outFile=open(outFileName, "w")

    for line in inFile:

        # split the lines
        words=line.split() 

        # remove all words less than 3 characters
        words = [word for word in words if len(word)>3]

        # make the list a set, so all duplicates are removed
        no_dups = set(words)

        # if there are more words in the words list than the
        # no duplicate list, we must have a duplicate, so 
        # print the line
        if len(words) > len(no_dups):
            outFile.write(line+'\n') #write in the outFile 

#test case
inFileName="file.txt"
outFileName="file_1.txt"

duplicateWordLines(inFileName,outFileName)

Относительно ошибки i is undefined, давайте посмотрим на ваше значение l oop

for word in words: #for each word in words
            if og.count(i)>0 and line not in dups: #if the word appears more than once and not already in duplicates
                dups.append(line) #add to duplicates
            else: #if not a duplicate 
                og.append(i) #add to the original list - not to worry about it

Вы на самом деле не определяете i где угодно, ваш l oop определяет word. Вы смешиваете умный l oop, то есть for word for words с диапазоном l oop, как for i in range(0,len(words)). Если бы мы исправили ваш l oop, я думаю, это выглядело бы примерно так ...

for word in words: #for each word in words
            if og.count(word)>0 and line not in dups: #if the word appears more than once and not already in duplicates
                dups.append(line) #add to duplicates
            else: #if not a duplicate 
                og.append(word) #add to the original list - not to worry 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...