使用Regex将match的每个实例替换为不同的字符串

2024-09-30 22:28:28 发布

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

我目前正在研究“用python自动化无聊的东西”。我参加了第八章题为“疯狂Libs”的实践项目。任务如下:

Create a Mad Libs program that reads in text fles and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text fle may look like this:

The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.

The program would find these occurrences and prompt the user to replace them.

Enter an adjective: silly

Enter a noun: chandelier

Enter a verb: screamed

Enter a noun: pickup truck

The following text file would then be created:

The silly panda walked to the chandelier and then screamed. A nearby pickup truck was unaffected by these events.

The results should be printed to the screen and saved to a new text file.

我目前的计划如下:

#! python3
# Requests user for an ADJECTIVE, NOUN, ADVERB, and a NOUN
# Replaces the words ADJECTIVE/NOUN/ADVERB/NOUN with the input in a txt file
# Saves the new Mad Lib as a new txt file

import re

reADJECTIVE = re.compile(r'''(ADJECTIVE)''')
reNOUN = re.compile(r'''(NOUN)''')
reVERB = re.compile(r'''(VERB)''')

for i in range(1):
    # Gets user input for ADVECTIVE/NOUN/VERB/NOUN
    ADJECTIVE = input('Enter an adjective: ')
    NOUN = input('Enter a noun: ')
    VERB = input('Enter a verb: ')
    NOUN2 = input('Enter a noun: ')

    madLibFile = open('madlib%s.txt' % (i + 1))
    madLibFileContent = madLibFile.read()
    madLibFile.close()
    madLibFileContent = madLibFileContent.split('. ')
    print(madLibFileContent)

    newMadLib = re.sub(reADJECTIVE, ADJECTIVE, madLibFileContent[0])
    newMadLib = re.sub(reNOUN, NOUN, newMadLib)
    newMadLib = re.sub(reVERB, VERB, newMadLib)
    newMadLib = newMadLib + '. ' + re.sub(reNOUN, NOUN2, madLibFileContent[1])

    print(newMadLib)

对于给定的例子,这个程序可以工作,但是由于我用句号/句点分隔它读入的文件,它只在输入文件的格式为:

ADJECTIVE NOUN ADVERB. NOUN.

并且不适用于任何其他格式,例如:

ADJECTIVE NOUN. ADVERB NOUN.

我最初的想法是使用regex模式:

^{pr2}$

如果我们假设任何给定的Mad Lib都遵循相同的形容词-名词-动词-名词的模式,那么这个方法是可行的。在

如果我使用:

re.sub(r'(NOUN)', replacement, someString)

它将用替换替换替换字符串中的NOUN实例。是否可以用不同的内容替换每个捕获组?在

感谢您抽出时间,我希望问题足够清楚:)


Tags: andthetotextreinputfileadjective
2条回答

诀窍是在re.sub中使用一个函数来代替替换字符串。这是一个粗糙的方法。在

import re

sentence = 'The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.'

def consider(matchobj):
    content = matchobj.group()
    if content in ['NOUN', 'ADJECTIVE', 'ADVERB', 'VERB']:
        return input('Please enter ' + content)
    else:
        return content

print (re.sub('[A-Z]+', consider, sentence))

我没有费心用你的话,只是当时我脑子里出现的任何东西。这是它在使用中的样子。在

^{pr2}$

编辑:根据评论添加。

import re

partsOfSpeech = ['NOUN', 'ADJECTIVE', 'ADVERB', 'VERB']
replacements = {_:'' for _ in partsOfSpeech}

for r in replacements:
    replacements[r] = input('Please enter ' + r.lower() + ': ')

madLibs = [
    'The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.',
    'A NOUN ADVERB decided to VERB the NOUN'
    ]

def consider(matchobj):
    content = matchobj.group()
    if content in partsOfSpeech:
        return replacements[content]
    else:
        return content

for madLib in madLibs:
    print (re.sub('[A-Z]+', consider, madLib))

结果:

Please enter adjective: vast
Please enter adverb: smoothly
Please enter verb: went
Please enter noun: bear
The vast panda walked to the bear and then went. A nearby bear was unaffected by these events.
A bear smoothly decided to went the bear

这是我的代码:

#! python3
# Mad Libs program to replace ADJECTIVE, NOUN, ADVERB, or VERB
import re,os
dir=os.getcwd()
readFile=open(dir)
contents=readFile.read()
readFile.close()
content=contents.split()

好的,所以上面的行正在打开文件,并且在contents中存储了文件的全部内容。在content中,单个单词是独立存储的。在

^{pr2}$

regex1负责替换动词、形容词、名词和副词的单个输入。content[i]和{}确保位置和正确的单词被替换。在

contents=' '.join(content)
print(contents)
writeFile=open(dir,'w')
writeFile.write(contents)
writeFile.close()

请随意纠正我,或用较短的方法解决这个问题。希望它能解决你的问题。在

相关问题 更多 >