我需要讓用戶創建 madlib,用戶可以在其中輸入一個 madlib 供其他人使用。輸入將是這樣的:
The (^noun^) and the (^adj^) (^noun^)
我需要在 (^ 和 ^) 之間拉任何東西,這樣我就可以用這個詞來編碼,這樣我就會得到另一個輸入提示來完成 madlib。
input('Enter "word in-between the characters":')
這是我現在的代碼
madlib = input("Enter (^madlib^):")
a = "(^"
b = "^)"
start = madlib.find(a) len(a)
end = madlib.find(b)
substring = madlib[start:end]
def mad():
if "(^" in madlib:
substring = madlib[start:end]
m = input("Enter " substring ":")
mad = madlib.replace(madlib[start:end],m)
return mad
print(mad())
我錯過了什么?
uj5u.com熱心網友回復:
您可以re.finditer()通過收集.span()每場比賽的來相當干凈地做到這一點!
import re
# collect starting madlib
madlib_base = input('Enter madlib base with (^...^) around words like (^adj^)): ')
# list to put the collected blocks of spans and user inputs into
replacements = []
# yield every block like (^something^) by matching each end and `not ^` inbetween
for match in re.finditer(r"\(\^([^\^] )\^\)", madlib_base):
replacements.append({
"span": match.span(), # position of the match in madlib_base
"sub_str": input(f"enter a {match.group(1)}: "), # replacement str
})
# replacements mapping and madlib_base can be saved for later!
def iter_replace(base_str, replacements_mapping):
# yield alternating blocks of text and replacement
# skip the replacement span from the text when yielding
base_index = 0 # index in base str to begin from
for block in replacements_mapping:
head, tail = block["span"] # unpack span
yield base_str[base_index:head] # next value up to span
yield block["sub_str"] # string the user gave us
base_index = tail # start from the end of the span
# collect the iterable into a single result string
# this can be done at the same time as the earlier loop if the input is known
result = "".join(iter_replace(madlib_base, replacements))
示范
...
enter a noun: Madlibs
enter a adj: rapidly
enter a noun: house
...
>>> result
'The Madlibs and the rapidly house'
>>> replacements
[{'span': (4, 12), 'sub_str': 'Madlibs'}, {'span': (21, 28), 'sub_str': 'rapidly'}, {'span': (29, 37), 'sub_str': 'house'}]
>>> madlib_base
'The (^noun^) and the (^adj^) (^noun^)'
uj5u.com熱心網友回復:
您的mad()函式只執行一次替換,并且只呼叫一次。對于具有三個必需替換的示例輸入,您只會得到第一個noun. 此外,mad()取決于在函式外部初始化的值,因此多次呼叫它是行不通的(它將繼續嘗試對相同的substring等進行操作)。
要修復它,您需要使其mad()對您提供的任何文本進行一次替換,而不管函式之外的任何其他狀態;然后你需要呼叫它,直到它替換了所有的單詞。您可以通過mad回傳一個標志來指示它是否找到了可以替代的任何東西,從而使這變得更容易。
def mad(text):
start = text.find("(^")
end = text.find("^)")
substring = text[start 2:end] if start > -1 and end > start else ""
if substring:
m = input(f"Enter {substring}: ")
return text.replace(f"(^{substring}^)", m, 1), True
return text, False
madlib, do_mad = input("Enter (^madlib^):"), True
while do_mad:
madlib, do_mad = mad(madlib)
print(madlib)
Enter (^madlib^):The (^noun^) and the (^adj^) (^noun^)
Enter noun: cat
Enter adj: lazy
Enter noun: dog
The cat and the lazy dog
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/374756.html
