python - 读取txt文件寻找匹配的混拼单词
PHPz
PHPz 2017-04-18 09:46:50
0
2
646

有一个类似字典的txt文件,读取后输入一段混乱的字母寻找匹配的单词(Word Jumble)。
并且print在这么多数量的单词中有几个是匹配的
输出结果应该类似

  $ python3 jumbler.py trsesi dict.txt
  resist
  sister
  2 matches in 41238 words
  $ python3 jumbler.py rayin dict.txt
  rainy
  1 match in 41238 words
  $ python3 jumbler.py tororo dict.txt
  No matches
  $ python3 jumbler.py taroro dict.txt
  orator
  1 match in 41238 words

字典的文件类似

a
aardvark
abaci
aback
abacus
abaft
abalone
abandon
abandoned
abandonment
abase
abasement
abash
abashed
abashedly
abashment
abate
abatement
abattoir
abbe
abbess
abbey
abbot
abbreviate
abbreviated
abbreviation
abdicate
abdication
abdomen
abdominal

我写的代码如下

import argparse

def jumbler(jumble, dict_file_name):
    """
    supply an excellent docstring here
    """

    # first you must open the file

    # second you must read each word from the file and perform an
    # appropriate comparison of each with 'jumble'; you need to count the
    # number of lines read from the file

    # if a word matches 'jumble', you are to print the word on a line by itself

    # after you have read each word from the file and compared, you need to
    # close the file

    # assume that there were MATCHES words that matched, and NLINES in the file
    # if there was a single match, you need to print
    # "1 match in NLINES words", where NLINES is replaced by the value of NLINES
    # if there were two or more matches, you need to print
    # "MATCHES matches in NLINES words"
    # if there were no matches, you need to print
    # "No matches"
    wordlist = []
    dictionary = open(dict_file_name,"r")
    for line in dictionary.readlines():
        wordlist.extend(line.split(','))#修改后
    for word in wordlist:
        if sorted(str(jumble))==sorted(str(word)):
            print(word+"\n")
        else:
            print("No matches")
    dictionary.close()



def main():
    """
    collect command arguments and invoke jumbler()
    inputs:
        none, fetches arguments using argparse
    effects:
        calls jumbler()
    """
    parser = argparse.ArgumentParser(description="Solve a jumble (anagram)")
    parser.add_argument("jumble", type=str, help="Jumbled word (anagram)")
    parser.add_argument('wordlist', type=str,
                        help="A text file containing dictionary words, one word per line.")
    args = parser.parse_args()  # gets arguments from command line
    jumble = args.jumble
    wordlist = args.wordlist
    jumbler(jumble, wordlist)

if __name__ == "__main__":
    main() 

但是打出来是一行行no matches....求大神赐教

我根据两位评论修改了list.extend,但是结果还是满满的no matches..不是很理解

ps.我们作业都是要求在终端run的所以会有额外的代码

我的output如下

No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
No matches
PHPz
PHPz

学习是最好的投资!

모든 응답(2)
左手右手慢动作

먼저 string.split()은 문자열을 목록으로 분할하고 list.append()는 전체 매개변수를 목록에 요소로 추가합니다. 따라서 코드에

를 추가합니다. 으아악

은 단어 목록을 목록의 목록으로 만듭니다. 즉, 단어 목록의 각 요소는 예상한 단일 단어가 아닌 목록입니다.

을 사용해야 합니다. 으아악

또는

으아악

두 번째로, readlines()에서 반환된 문자열에는 다음 코드와 같이 줄 끝에 개행 문자가 포함되어 있습니다.

으아악

line.split(',')으로 바꿔야 합니다. line.split()

참조코드는 다음과 같습니다.

으아악

Peter_Zhu

이유는 간단합니다. 문제는 여기에 있습니다.

으아악

코드를 약간 수정할 수 있습니다.

으아악

하지만 list에 단어를 모두 저장하면 메모리가 많이 소모됩니다. 특히 동의어 사전 파일이 크면...
개인적으로는 list에 일치하는 단어만 저장하는 것이 좋습니다. 일치하는 항목에 주의를 기울일 필요가 없습니다.

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿