如何加入() - 第8章自动化无聊的东西

时间:2016-06-06 20:58:30

标签: python

来自Automate The Boring Stuff with Python book: "创建一个Mad Libs程序,该程序读入文本文件,并允许用户在文本文件中出现单词ADJECTIVE,NOUN,ADVERB或VERB的任何地方添加自己的文本。例如,文本文件可能如下所示:

ADJECTIVE熊猫走向NOUN,然后是VERB。附近有一个NOUN 不受这些事件的影响。

程序会找到这些事件并提示用户替换它们。"

我差不多完成了,但我似乎无法弄清楚如何加入文件的最后一个列表。我已经在线查看了这些方法。我没有从连接中获取字符串,而是获得了空格。 ' .join(mod4)分隔每个列表字符串值中的字母。 [' A' ,'在' ,' t w o' ,' a n d' ,'这是' ,'你好吗? ] 其他所有工作都可以完成。

#! python3

import re

madText = open('madText.txt', 'w')

text = 'An ADJECTIVE, a NOUN, an ADVERB and a VERB.'

madText.write(text)
madText.close()

content = re.split('\W+', text)

for i in content:

    if i == "ADJECTIVE":
        replaceRegex = re.compile(r'(ADJECTIVE)')
        print('Enter an ADJECTIVE:')
        ADJECTIVE = input()
        output = replaceRegex.sub(ADJECTIVE, str(content))

    elif i == "NOUN":
        replaceRegex = re.compile(r'(NOUN)')
        print('Enter a NOUN:')
        NOUN = input()
        output = replaceRegex.sub(NOUN, str(output))

    elif i == "ADVERB":
        replaceRegex = re.compile(r'(ADVERB)')
        print('Enter an ADVERB:')
        ADVERB =  input()
        output = replaceRegex.sub(ADVERB, str(output))

    elif i == "VERB":
        replaceRegex = re.compile(r'(VERB)')
        print('Enter a VERB:')
        VERB = input()
        output = replaceRegex.sub(VERB, str(output))

content = re.split('\W+', output)
#content = list(output.split(' '))
content = ' '.join(content)
print(content)
madLibs = open('madText2.txt', 'w')
madLibs.write(content)
madLibs.close()

5 个答案:

答案 0 :(得分:3)

您有一个基本的假设,即阻止您完成此操作。您对mod4的分配基于之前的作业及其顺序。

相反,您应该做的是将output变量初始化为[],并在循环content时将字词附加到其中。您可以添加adlib单词和真实单词。

构建输出列表然后后,使用joinoutput转换为字符串。

此外,使用regex是过度的。我们假设您在循环之前已经创建了output = []

if i == 'NOUN':
   print('Enter a NOUN:')
   noun = input()  # raw_input() on Python 2
   output += noun
[...]

现在,当您点击每个adlib令牌时,请将其替换为输入的文本并构建输出列表。

答案 1 :(得分:0)

这是我的答案。我想我应该在发布上述内容的4分钟内得到-2次弃牌。 :)

import re

madText = open('madText.txt', 'w')
text = 'An ADJECTIVE, a NOUN, a VERB and an ADVERB and a NOUN.'
madText.write(text)
madText.close()
content = re.split('(\W+)', text)

for i in content:
    if i == 'NOUN':
        content.insert(content.index('NOUN'), input('Replace ' + i + ': '))
        content.remove('NOUN')
    elif i == 'VERB':
        content.insert(content.index('VERB'), input('Replace ' + i + ': '))
        content.remove('VERB')
    elif i == 'ADVERB':
        content.insert(content.index('ADVERB'), input('Replace ' + i + ': '))
        content.remove('ADVERB')
    elif i == 'ADJECTIVE':
        content.insert(content.index('ADJECTIVE'), input('Replace ' + i + ': '))
        content.remove('ADJECTIVE')

content = ''.join(content)
print(content)
madLibs = open('madText2.txt', 'w')
madLibs.write(content)
madLibs.close()

答案 2 :(得分:0)

这是我针对同一练习的解决方案。

import os, re

def start():
    fileName = input('Enter the file name: ')
    exist_fileName = os.path.abspath(fileName)
    if os.path.exists(exist_fileName) == True:

        text_file = open(exist_fileName)
        text_content = text_file.read()
        text_file.close()
        print(text_content)


        text_regex = re.compile(r'ADJECTIVE|NOUN|VERB|ADVERB')
        match_text = text_regex.findall(text_content)

        for match in match_text:
            user_input = input('Enter ' + match + ': ')
            text_content = text_content.replace(match, user_input, 1)
        print(text_content)

        new_fileName = 'new_' + fileName
        new_file = open(new_fileName, 'w')
        new_file.write(text_content)
        new_file.close()

    else:
        print('The file you have entered does not exist. Please enter a valid file name.')
        start()

start()

答案 3 :(得分:0)

这是我针对同一问题的代码,这要感谢上面的Alex Antony的帮助。

import re

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

madlib_file = open('madlib.txt', 'w')
madlib_file.write(madlib_text)

madlib_regex = re.compile(r'[A-Z]{2,}')
mo = madlib_regex.findall(madlib_text)

for x in mo:
    if x == 'ADJECTIVE':
        prompt = input('Enter an adjective: ')
    else:
        prompt = input(f'Enter a {x.lower()}: ')
    madlib_text = madlib_text.replace(x, prompt, 1)

print('\n' + madlib_text)

user_madlibs = open('completed_madlibs.txt', 'w')
user_madlibs.write(madlib_text)

user_madlibs.close()
madlib_file.close()

答案 4 :(得分:0)

与上述类似的方法。评论应具有相当的描述性:

#! python3
# madLibs.py - Prompts user for a text file.
#   At each occurence of ADJECTIVE, NOUN, ADVERB, and VERB, user is prompted for a word.
#   The user's word of choice replaces the placeholder.
#   The file is overwritten with the user's word choices in the same structure.

# Import modules.
import re
from pathlib import Path

# Prompt user for file input.
file = input('Please input a file (path).\n')

# Store the file's contents as a string variable.
filecontent = open(file).read()

# Breaks the string into a list with each word, punctuation mark, or space conserved at an index.
listRegex = re.findall(r"[\w']+|[.,!?;]|[\s]", filecontent)

# Scan through the list and look for placeholder words.
#   At each instance, prompt the user for a replacement and make the substitution.
for character in range(len(listRegex)):
    if listRegex[character] == 'ADJECTIVE':
        adjective = input('Enter an adjective.\n')
        listRegex[character] = adjective
    elif listRegex[character] == 'NOUN':
        noun = input('Enter a noun.\n')
        listRegex[character] = noun
    elif listRegex[character] == 'ADVERB':
        adverb = input('Enter an adverb.\n')
        listRegex[character] = adverb
    elif listRegex[character] == 'VERB':
        verb = input('Enter a verb.\n')
        listRegex[character] = verb

# Convert the new list into a new string.
string = ''
for character in listRegex:
    string += character
print(string)

# Overwrite the original file.
Path(file).write_text(string)