0

我一直在关注“自动化无聊的东西”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()

谢谢,

斯图尔特

4

1 回答 1

0

我拿走了你的代码并评论了我要改变的地方:

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()

# Use sensible variable names
print('Enter an adjective: ')
adjective = input()
print('Enter a noun: ')
noun1 = input()
print('Enter a verb: ')
verb = input()
print('Enter a noun: ')
noun2 = input()

# Use "with" or close the file afterwards, mention the mode to open
with open('Mad Libs.txt', 'r') as file:
    text = file.read()
# or
file = open('Mad Libs.txt', 'r')
text = file.read()
file.close()

# Use a Dictionary for the Replacements and the .replace method
replacements = {
'ADJECTIVE':adjective
'NOUNONE':noun1
'VERB':verb
'NOUNTWO':noun2
}

for a, b in replacements.items():
    text = text.replace(a, b)

# Print to screen.
print('\n\n')
print(text)

#Print the new text to file.
file = open('Mad Libs.txt', 'a')
file.write('\n\n' + text)
file.close()

想想用“with”打开文件,舒服多了。欣赏这本书,我也喜欢它!

于 2020-07-12T14:50:04.913 回答