![](/img/trans.png)
[英]Python regular expression that will find words made out of specific letters. Letters must be used once only
[英]To find words but only with requested number of specific letters
我正在編寫一個腳本,該腳本應該查找包含用戶輸入的給定字母的單詞。 然而,該腳本並不完全按照我想要的方式工作。 例如,如果我輸入字母:stop 腳本會打印出我輸入但重復的單詞,例如:stop、stoper、stereotype。 不應該有“Stereotype”這個詞,因為我只輸入了一個:“e”和“t”
letters = input('letters: ')
words = open('newwords').read().splitlines()
#print (words)
print(".......................")
for word in words:
if all(x in word for x in letters):
for x in letters:
if word.count(x) == letters.count(x):
print(word)
我不知道你的“新詞”長什么樣。 我嘗試這樣的事情:
stop
stoper
stereotype
代碼與你的相同,除了words = open('test.txt').read().splitlines()
letters: stop
.......................
stop
stop
stop
stop
stoper
stoper
stoper
stoper
stereotype
stereotype
stereotype
您的for x in letters
letter 一次檢查一個字母。 由於 "s"、"o" 和 "p" 的計數相同,所以構造型打印了 3 次(不是 4 次,因為 "t" 的計數不同)。
您可以將最后一部分更改為此,以便在檢查所有字母計數后才打印出該單詞。
for word in words:
if all(word.count(x) == letters.count(x) for x in letters):
print(word)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.