![](/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.