首页 > 解决方案 > 用 Python 自动化无聊的东西:Mad Libs

问题描述

这是我的第一个程序之一。我需要添加一个异常,因为我的 for 循环总是以“AttributeError”结束。解决它的想法?我发现其他人已经为这个问题发布了他们自己的解决方案(即替换文本文件中的关键字),但我不想只是复制它们。

我知道可能有一些方法可以缩短代码,但我还没有弄清楚(还)。

import re, os

#Check if a story template finns, else create a new one.
if os.path.exists('madlibstemplate.txt') == False:
    print('No story template found, creating a new file.')
    mad_libs_file = open('madlibstemplate.txt', 'w')
    mad_libs_file.write('Long time ago, the ADJECTIVE NOUN lived in the ADJECTIVE NOUN. \
There was only a neighbour: the ADJECTIVE NOUN. The neighbour decided to ADVERB VERB \
the rival. However, the ADJECTIVE NOUN managed to VERB the evil neighbour.')
    mad_libs_file.close()
else:
    print('An empty template file found!')

# Open file and save the text under 'content'
mad_libs_file = open('madlibstemplate.txt')
content = mad_libs_file.read()
# To be able to search for the placeholder keywords
mad_regex = re.compile('NOUN|ADJECTIVE|VERB|ADVERB')
search = mad_regex.search(content)
# The story is edited multiple times and saved under "result"
result = search.group()
# Just to loop the for loop enough times
amount = len(mad_regex.findall(content))

# Editing the story 'amount' times and asking to enter a replacement word
for i in range(amount):
    try:
        if result == 'NOUN':
            print('Enter a noun:')
            k = input()
            mad_regex.sub(k, content, 1)
            content = mad_regex.sub(k, content, 1)
            search = mad_regex.search(content)
            result = search.group()
        elif result == 'VERB':
            print('Enter a verb:')
            k = input()
            mad_regex.sub(k, content, 1)
            content = mad_regex.sub(k, content, 1)
            search = mad_regex.search(content)
            result = search.group()
        elif result == 'ADJECTIVE':
            print('Enter an adjective:')
            k = input()
            mad_regex.sub(k, content, 1)
            content = mad_regex.sub(k, content, 1)
            search = mad_regex.search(content)
            result = search.group()
        elif result == 'ADVERB':
            print('Enter an adverb:')
            k = input()
            mad_regex.sub(k, content, 1)
            content = mad_regex.sub(k, content, 1)
            search = mad_regex.search(content)
            result = search.group()
    except AttributeError: #Always ends with error for some reason, so an exception.
        print('\nThis is your new story: \n \n' + content + '\n')

# Creates a new file for the new story        
print('Please name your new file.')
k = input()
new_file = open('%s.txt' % (k), 'w')
new_file.write(content)
new_file.close()

标签: python

解决方案


您的代码中的问题是您没有检查返回值。

for i in range(amount):
    try:
        if result == 'NOUN':
            print('Enter a noun:')
            k = input()
            mad_regex.sub(k, content, 1)
            content = mad_regex.sub(k, content, 1)
            search = mad_regex.search(content)  # This returns None when it doesn't match
            result = search.group() # Search is now None, and you get your exception

解决方案是检查结果,mad_regex.search如果是None,请不要尝试更新结果,因为由于您的 for 循环条件,您的循环无论如何都会完成。


推荐阅读