【发布时间】:2020-11-01 20:05:03
【问题描述】:
我一直在关注“自动化无聊的东西”Python 课程。 一个练习项目需要根据一些用户输入更改 txt 文件中的一段文本。
我的尝试在下面,但我的思维方式仍然是完成工作的冗长方式。我不觉得我的代码是最有效的“pythonic”方法。
有没有更好、更有效的方法来做到这一点?
感谢任何反馈(为了清楚起见,我在代码中留下了注释)。
Replace the words ADJECTIVE, NOUN, ADVERB and NOUN in a passage of text.
Use prompts to input the words to be used.
Print to sceen and save to file.
#Prompt user for the words to add
from pathlib import Path
file = open('Mad Libs.txt', 'w')
file.write('The ADJECTIVE panda walked to the NOUNONE and then VERB. A nearby NOUNTWO was unaffected
by these events.')
file.close()
print('Enter an adjective: ')
a = input()
print('Enter a noun: ')
nOne = input()
print('Enter a verb: ')
v = input()
print('Enter a noun: ')
nTwo = input()
#Open the file and split the passage into a list??
file = open('Mad Libs.txt')
text = file.read().split()
#Find words in file to be replaced.
aIndex = text.index('ADJECTIVE')
nOneIndex = text.index('NOUNONE')
vIndex = text.index('VERB.')
nTwoIndex = text.index('NOUNTWO')
#Replace each word with the inputs and close.
text[aIndex] = a
text[nOneIndex] = nOne
text[vIndex] = v+'.'
text[nTwoIndex] = nTwo
#Join text back to a readable passage and print to screen.
newText = " ".join(text)
print('\n\n')
print(newText)
#Print the new text to file.
file = open('Mad Libs.txt', 'a')
file.write('\n\n' + newText)
file.close()
谢谢,
斯图尔特
【问题讨论】:
-
Given pythons
list.index只找到第一次出现,你会发现它并没有像希望的那样替换所有内容。我确信有更好的方法可以做到这一点,但是我会使用 for 循环代替索引,这样您就可以检查所有内容,而不仅仅是第一件事 -
谢谢,伊桑。是的,原文只有两个名词都显示为“名词”。我将它们更改为 nounone 和 nountwo,以便索引可以工作。我知道会有更好的方法,所以我希望有人能添加到这个......
-
如果您需要评论,请转到页面CodeReview
-
BTW
index()有更多选项index(item, start, end),您可以使用第一个noun的位置开始搜索下一个noun-first = index("noun")和second = index("noun", first+1)