[英]Comparing words in 2 different list in python and replacing the found words with "*" in output
我試圖使用戶作為輸入提供的消息發出嗶嗶聲,好像輸入是“到底是什么”,其中“見鬼”出現在名為“banned.txt”的文件中的禁用詞列表中,以便輸出變為“什么**”。
我是 python 的新手,到目前為止,我已經從傳遞的輸入中列出了兩個列表以及存在禁用詞的列表,我在比較這兩個列表中的詞時遇到了麻煩,有人可以解釋我如何解決這個問題。
from cs50 import get_string
import sys
def main():
if len(sys.argv) != 2:
print("Usage: python bleep.py dictionary")
exit(1)
print("What message would you like to censor?")
msg=get_string()
infile=open(sys.argv[1],'r')
bannedwords=[infile.read().split("\n")]
userwords=[msg.split(" ")]
for uword in userwords:
for bword in bannedwords:
if(uword==bword)
#do something.....but its not comparing words
if __name__ == "__main__":
main()
輸入:什么鬼
預期輸出:什么****
不要將您的 msg 拆分成一個列表,而是在列表中搜索被禁止的詞。
for word in bannedwords:
if word in msg:
new_word = "*" * len(word)
new_msg = msg.replace(word, new_word)
如果您想直接測試它,請使用:
bannedwords = ["banned", "other"]
msg = "the next word is banned"
new_msg = ""
for word in bannedwords:
if word in msg:
new_word = "*" * len(word)
new_msg = msg.replace(word, new_word)
print(new_msg)
你的問題在於:
bannedwords=[infile.read().split("\n")]
userwords=[msg.split(" ")]
split 命令已經將單詞放入一個數組中,因此您將它們包裝在兩個數組中,得到:
[['heck', '']]
[['what', 'the', 'heck']]
分別作為禁用詞列表和消息中的詞列表。
從定義中刪除[]
並使用:
bannedwords=infile.read().split("\n")
userwords=msg.split(" ")
並且您的代碼應該可以正常工作。 您也可以檢查每個單詞是否在禁用單詞列表中,例如:
bannedwords=infile.read().split("\n")
userwords=msg.split(" ")
for uword in userwords:
# An easier way to check if the word is banned.
if(uword in bannedwords):
# If it's banned, print one * for each letter in the word.
print("*" * len(uword))
else:
print(uword)
'what the heck' 的輸入給出了以下輸出:
what
the
****
以下解決方案可能適合您。 這也會從msg
字符串的末尾刪除標點符號,同時將msg
bannedwords
替換為“*”:
from string import punctuation
bannedwords = ["heck", "darn"]
msg = input("What message would you like to censor?: ")
for word in msg.rstrip(punctuation).split(' '):
if word in bannedwords:
new_word = '*' * len(word)
msg = msg.replace(word, new_word)
print(msg)
#Output:
What message would you like to censor?: What the heck?
What the ****?
#Another attempt:
What message would you like to censor?: darn it!
**** it!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.