【问题标题】:Automate the boring stuff with python chapter_8 MadLibs使用python第8章Mad Libs自动化无聊的东西
【发布时间】:2019-10-09 09:57:41
【问题描述】:

你好,这个练习说: 创建一个 Mad Libs 程序,该程序读取文本文件并允许用户在文本文件中出现单词 ADJECTIVE、NOUN、ADVERB 或 VERB 的任何位置添加自己的文本。

textfile = 形容词 panda 走到名词和动词。附近的一个名词是 不受这些事件的影响。

到目前为止我所拥有的是:

import re
#filename = input('Input the Filename: ')

with open('madlibs.txt') as file:
    content = file.read()
file.close()

regex = re.compile(r'ADJECTIVE|NOUN|VERB|ADVERB')
#regex = re.compile('[A-Z]{3,}')
matches = regex.findall(content)
#newWord = []

for word in matches:
    user_input = input('Enter %s: ' % word)
  # newWord.append(user_input)
    new_content = content.replace(word,user_input,1)
print(new_content)

我的输入是:

Enter ADJECTIVE: heavy
Enter NOUN: whale
Enter VERB: runs
Enter NOUN: door

我的输出:

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

有人可以向我解释我做错了什么吗?由于某种原因,我似乎无法更改 ADJECTIVE 和 VERB,我还尝试了大写的注释正则表达式,它也是如此,所以问题出在其他地方。

【问题讨论】:

  • 我还必须将 content.replace(word,user_input) 替换为 content.replace(word,user_input,1) 以便正确替换名词

标签: python


【解决方案1】:

您需要更改 content,但因为您不是,它会覆盖您的更改,直到最后一个字:

for word in matches:
    user_input = input('Enter %s: ' % word)
    content = content.replace(word,user_input)  # overwrite content here

print(content)

或者,如果您希望保持 content 不变:

new_content = content 

for word in matches:
    user_input = input('Enter %s: ' % word)
    new_content = new_content.replace(word,user_input)  # overwrite new_content here

print(new_content)

python 中的字符串是不可变的,这意味着它们不会就地更改,而是必须重新分配:

somestring = "this is a string"

for word in ["is", "a"]:
    newstring = somestring.replace(word, "aaaa")

print(newstring)
# this is aaaa string

print(somestring)
# this is a string

请注意,somestring 仍然是原始值。第一个replace 确实发生了,只是在重新分配somestring.replace("a", "aaaa") 的结果时被覆盖了。

分为步骤:

somestring = "this is a string"

newstring = somestring.replace("is", "aaaa")
# this aaaa a string

newstring = somestring.replace("a", "aaaa")
# this is aaaa string

【讨论】:

    【解决方案2】:
    #! /usr/bin/python3
    # mad_libs.py - Playing mad libs game
    # Usage: python3 mad_libs.py save - Save a mad lib phrase from clip board
    #        python3 mad_libs.py - Play the mad libs game.
    # Caution: Must save at least one phrase before playing.
    
    import shelve, pyclip, random, sys, re
    import pyinputplus as pyi
    
    # Open shelve file
    shelfFile = shelve.open('mad_libs')
    
    # Add phrase to the database by pasting from clipboard
    if len(sys.argv) == 2 and sys.argv[1] == 'save':
        shelfFile[str(len(shelfFile))] = pyclip.paste().decode()
        print("Phrase saved.")
        sys.exit()
    
    # Get a random phrase from database and display
    phrase = shelfFile[str(random.randrange(len(shelfFile)))]
    
    # Regex for finding match
    matLibsRegex = re.compile(r'(ADJECTIVE)|(NOUN)|(VERB)|(ADVERB)')
    
    print(phrase)
    while True:
        # Find all the matches and replace with user's input
        match = matLibsRegex.search(phrase)
    
        if match == None:  # Return None if there is no match
            break
    
        prompt = f"Enter an {match.group().lower()}: " if match.group(
        )[0] in 'Aa' else f"Enter a {match.group().lower()}: "
    
        substitute = pyi.inputStr(prompt)
        phrase = phrase.replace(match.group(), substitute, 1)  # Replace the fill-in space with user's input
    
    # Print the final phrase and save it to file
    print(phrase)
    
    result = open('mad_libs_result.txt', 'a')
    result.write(phrase + '\n')
    result.close()
    shelfFile.close()
    

    我希望这可以增强您的代码。

    因为这篇文章是关于疯狂的库,我想在这里为即将到来的学习者提供我的解决方案。我结合了 Mad Libs 练习和 Extend Multi-Clipbaord 练习的功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      相关资源
      最近更新 更多