首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Madlib自动化无聊的事情

Python Madlib自动化无聊的事情
EN

Stack Overflow用户
提问于 2016-12-16 12:36:27
回答 1查看 389关注 0票数 0

我从“在Python中自动化无聊的事情”一书中用Python语言编写了一个MadLib程序。我确信我的程序会这样做,但当用户需要输入时,我总是得到这个奇怪的"NameError“。

这是我的代码。我的计划是,一旦看到消息成功加入,就将内容写入文件。

代码语言:javascript
复制
#!/usr/local/bin/python3

import sys

'''
Create a Mad Libs program that reads in text files and lets the user add
their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB
appears in the text file.
'''

breaks = ["noun", "verb", "adverb", "adjective"]


'''Program Usage and Exit Case'''
if len(sys.argv) < 2:
    print("Usage: ./mad.py <FileName>")
    sys.exit()

'''Read in File and Store Contents in Array'''
file = open(sys.argv[1])
chunk = str(file.read()).split()

****'''Search through text for keywords'''
for word in chunk:
    if word.lower() in breaks:
        chunk[word] = input("Enter %s: " %word)****

newMessage = " ".join(chunk)
print(newMessage)


file.close()
EN

回答 1

Stack Overflow用户

发布于 2016-12-16 13:03:27

我认为问题在于代码实际上是在Python2中运行的,其中输入函数实际上试图运行用户的输入,就像它是代码一样。比较Python 2Python 3的input()文档。所以你会得到一个NameError,因为Python试图把你输入的东西当作一个变量,而这个变量并不存在。如果你想让它在Python2中工作,只需将input替换为raw_input即可。

您将遇到的另一个问题是

代码语言:javascript
复制
chunk[word] = input("Enter %s: " %word)

将不起作用,因为word是一个字符串,而chunk需要一个数字作为列表中的索引。要解决这个问题,只需在for循环中跟踪当前索引即可。一种特殊的Pythonic方法是使用enumerate函数,如下所示:

代码语言:javascript
复制
for i, word in enumerate(chunk):
    if word.lower() in breaks:
        chunk[i] = input("Enter %s: " %word)

现在一切都应该正常了!修复后的Python 3版本如下:

代码语言:javascript
复制
#!/usr/local/bin/python3
import sys

'''
Create a Mad Libs program that reads in text files and lets the user add
their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB
appears in the text file.
'''

breaks = ["noun", "verb", "adverb", "adjective"]


'''Program Usage and Exit Case'''
if len(sys.argv) < 2:
    print("Usage: ./mad.py <FileName>")
    sys.exit()

'''Read in File and Store Contents in Array'''
file = open(sys.argv[1])
chunk = str(file.read()).split()

'''Search through text for keywords'''
for i, word in enumerate(chunk):
    if word.lower() in breaks:
        chunk[i] = input("Enter %s: " %word)

newMessage = " ".join(chunk)
print(newMessage)


file.close()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41177344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档