自动将单词分成字母?

时间:2014-01-17 08:14:31

标签: python dictionary argv sorted sys

所以我有这段代码:

import sys  ## The 'sys' module lets us read command line arguments

words1 = open(sys.argv[2],'r') ##sys.argv[2] is your dictionary text file    
words = str((words1.read()))

def main():

    # Get the dictionary to search 
    if (len(sys.argv) != 3) :
        print("Proper format: python filename.py scrambledword filename.txt")
        exit(1)  ## the non-zero return code indicates an error
    scrambled = sys.argv[1]
    print(sys.argv[1])
    unscrambled = sorted(scrambled)
    print(unscrambled)

    for line in words:
        print(line)

当我打印单词时,它会打印字典中的单词,一次一个单词,这很棒。但是,一旦我尝试用我最后两行中的那些单词做任何事情,它会自动将单词分成字母,并在每个单词的每行打印一个字母。反正有没有把话放在一起?我的最终目标是执行ordered = sorted(line),然后if(ordered == unscrambled)让它从字典中打印原始单词?

2 个答案:

答案 0 :(得分:2)

您的文字是str的一个实例。您应该使用split来迭代单词:

for word in words.split():
    print(word)

答案 1 :(得分:1)

for - 循环从您传递的“序列”中一次获取一个元素。您已将文件的内容读入单个字符串,因此python将其视为一系列字母。你需要的是自己将它转换成一个列表:将它拆分成一个你喜欢的字符串列表:

lines = words.splitlines()  # Makes a list of lines
for line in lines:
    ....

或者

wordlist = words.split()    # Makes a list of "words", by splitting at whitespace
for word in wordlist:
    ....