我是python的新手(或多或少)并且正在努力完成一项任务,我需要通过用户输入或任何更好/更容易的方式输入一个句子(最好是长一个,例如“我们昨天见面了”,但并不重要)。然后遍历所有字母,找到所有单词的所有可能的字母组合,并在由数千个单词(大约4 mb文件)组成的文件中找到它们的匹配,每个单词在一个单独的行上,如下所示:
fun
dog
whatever
coffee
cup
我和itertools.permutations
一起去了set
和intersection
。不用多说,这是我的代码到目前为止:
from itertools import permutations
def alpha_check():
"""check whether a sentence consists of only letters"""
sentence = str.lower(input('Type something in: '))
while not sentence.replace(' ', '').isalpha():
print(f"You typed in {sentence!s}. Only letters A-Z allowed, not case sensitive.")
sentence = input("Please, type something again: ")
return sentence
def file_iter(sentence: str):
my_set = set(line.strip() for line in open('file.txt'))
word_list = set(sentence.split())
for x in word_list:
temp = list(permutations(x))
for f in temp:
print(''.join(f), end=' ') # gets rid of commas etc.
inters = my_set.intersection(f)
return inters
print(file_iter(alpha_check()))
阿尔法检查目前不感兴趣,我只想让这个怪物工作。目前它输出这样的东西,授予我在提示后输入"map lake"
:
Type something in: map lake
lake laek lkae lkea leak leka alke alek akle akel aelk aekl klae klea kale kael kela keal elak elka ealk eakl ekla ekal {'l', 'e', 'a', 'k'}
和预期的输出将是map
和lake
排列,然后在输入和文件中找到交叉点。我搜索了很多SO和谷歌。发现了很多信息,但无论如何我都无法完成这项工作。这是我想出的最好的一个。另外,我不是要求一个完整的解决方案,只是为了帮助理解我做错了什么以及如何解决这个问题。线索,小贴士等谢谢!
更新:
def file_iter(sentence):
new_sentence = []
my_set = set(line.strip() for line in open('file.txt'))
word_list = sentence.split()
for words in word_list:
permutation = list(permutations(words))
permute_set = my_set.intersection(["".join(word) for word in permutation])
new_sentence += permute_set.union(word_list)
return print(' '.join(set(new_sentence)))
这提供了以下输出:
Type something in: we met each other
toher ache we haec throe other tem each theor ew met thore
如何将它们分成不同的句子?这些方面的东西:
we toher met ache
ew tem haec thore
我假设通过“找到所有可能的字母组合”,你实际上是指排列。如果是这种情况,您要做的是将单词的大列表存储在字典中,其中排序的字母为键,相应的单词列表(字谜)为值。
然后你可以翻阅句子中的单词并在字典中找到一个条目(使用单词的排序字母)来获得所有的字谜。
排序后的字母(wordKey)可以作为彼此字谜的单词的组标识符。所有字谜都会在字典中生成一个键,因此您无需费心排列。
以下是您可以通过以下方式构建解决方案的示例:
anagrams = dict()
for word in open("/usr/share/dict/words").read().split("\n"):
wordKey = "".join(sorted(word.lower()))
anagrams.setdefault(wordKey,[]).append(word)
sentence = "We met each other yesterday"
for word in sentence.split():
wordKey = "".join(sorted(word.lower()))
print(word, anagrams.get(wordKey,[word]))
根据笔记本电脑上的235K字词,产生以下输出:
We ['we']
met ['met']
each ['ache', 'each', 'haec']
other ['other', 'thore', 'throe', 'toher']
yesterday ['yesterday']
请注意,您的解决方案已接近正常。
f
中的my_set.intersection(f)
变量应该是temp
,因为f
仅仅是最后的排列。f
也可能没有包含你期望的内容。因为permutation(x)
将x
视为一个列表,它会产生一个结果(temp
),它是一个列表而不是一个字符串列表。my_set.intersection([ "".join(f) for f in
temp])
它可能会有用。inters
是否真的是你想要做的。len(my_set)
或前几个条目list(my_set)[:25]
,以确保你有文字而不是字母。[更新]将输出显示为单个单词列表:
sentence = "We met each other yesterday"
result = []
for word in sentence.split():
wordKey = "".join(sorted(word.lower()))
result += anagrams.get(wordKey,[]) + [word]
print(" ".join(set(result)))
# thore each other haec we met throe toher yesterday ache
[UPDATE2]时髦的句子
如果你想玩结果并构建所有可以使用字谜形成的句子,你需要浏览每个单词的anagram组并在每一步“乘以”组合:
from itertools import product
from itertools import product
funkySentences = [[]]
for word in sentence.split():
wordKey = "".join(sorted(word.lower()))
alternateWords = anagrams.get(wordKey,[word])
funkySentences = [ s+[w] for s,w in product(funkySentences,alternateWords) ]
funkySentences = set(" ".join(fs) for fs in funkySentences)
for fs in funkySentences:
print(fs)
这将打印:
we met haec throe yesterday
we met haec thore yesterday
we met haec toher yesterday
we met ache toher yesterday
we met haec other yesterday
we met each throe yesterday
we met each toher yesterday
we met ache other yesterday
we met each thore yesterday
we met ache throe yesterday
we met ache thore yesterday
we met each other yesterday
您也可以通过对每个这些时髦的句子应用排列来疯狂改变单词的顺序:
from itertools import chain,permutations
yodaSentences = chain(*[permutations(fs.split()) for fs in funkySentences])
yodaSentences = set(" ".join(ys) for ys in yodaSentences)
for ys in yodaSentences:
print(ys)
这将打印(尤达说):
ache we yesterday met other
other haec we met yesterday
yesterday met throe each we
haec throe yesterday met we
we yesterday met haec toher
yesterday we ache met throe
haec yesterday we other met
other yesterday met haec we
met we haec thore yesterday
each we yesterday other met
we ache yesterday other met
yesterday met toher we each
we met yesterday thore ache
... and many more ....