我有一个文本文件,这是一个没有空格的单词列表,例如“神经心理神经心理学神经心理学神经精神病学”等 我正在尝试构建一个程序,它将输入一个输入的单词并检查.txt文件中是否包含该单词的任何字谜,然后将它们添加到字典中。
到目前为止,我提出的代码是打印1个包含在words.txt中的1个排列的字典;
anagram_dict = {}
def anagram(word):
b = open('words.txt', 'r').readlines()
text = ''.join(line.strip() for line in b)
#print(len(text))
for i in range(len(text)-len(word)):
prop = text[i:i+len(word)]
if all(char in word for char in prop): #and all(prop.count(char) == prop.count(word) for char in prop):
anagram_dict[''.join(sorted(word))] = [prop]
print(anagram_dict)
anagram("demand")
问题在于它打印的排列不是一个字谜(我输入“需求”期待“疯狂”出来但它打印出文件中的“amamad”而不是anagram)我怎样才能做到如果排列是一个真正的字谜(相同的字母只是重新排列),它只打印字典?
我认为问题可能在于“如果所有(在支柱中用字符表示char):#和all(prop.count(char)== prop.count(word)for prop in prop):”< / p>
特别是当它运行时注释掉的部分只打印一个空字符串。
为此而道歉这么长时间我只是想确保自己解释一下。谢谢你的帮助。
答案 0 :(得分:0)
import com.myCompanyExample.gui.Layout
/*some comments here*/
@Layout
LayoutModel currentState() {
MyBuilder builder = new MyBuilder()
form example
title form{
row_1
row_1
row_n
}
return build.get()
}
@Layout
LayoutModel otherState() {
....
....
return build.get()
}
只是检查private void myReadFile(File fileLayout){
String line = null;
StringBuilder allText = new StringBuilder();
try{
FileReader fileReader = new FileReader(fileLayout);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
allText.append(line)
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file");
}
catch(IOException ex) {
System.out.println("Error reading file");
}
Pattern pattern = Pattern.compile("(?s)@Layout.*?return",Pattern.DOTALL);
Matcher matcher = pattern.matcher(allText);
while(matcher.find()){
String [] layoutBlock = (matcher.group()).split("\\r?\\n")
for(index in layoutBlock){
//check each line of the current block
}
}
的所有字母是否都在all(char in word for char in prop)
。
需求中的所有字母均为word
prop
,因此会显示在结果中。
"present"
存在问题(可能是拼写错误)。
应为"madden"
还有一个更好的选择,检查all(prop.count(char) == prop.count(word) for char in prop)
和all(prop.count(char) == word.count(char) for char in prop)
的排序版本是否相同。
prop