【问题标题】:Automatically separating words into letters?自动将单词分成字母?
【发布时间】:2014-01-17 16:31:22
【问题描述】:

所以我有这个代码:

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) 让它打印字典中的原始单词?

【问题讨论】:

  • 什么是words?你能告诉我你得到的样本输出和预期的输出吗?
  • 好吧,它打印了整个字典,所以它每行打印一个单词:aardvark abacus accusation adore,但在命令模块中每个单词都在自己的行中。我截图了。 i.imgur.com/oM2aEf2.png

标签: python dictionary argv sorted sys


【解决方案1】:

您的话是str 的一个实例。您应该使用split 来遍历单词:

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

【讨论】:

  • 非常感谢。你是救生员。
【解决方案2】:

for-loop 从您传递的“序列”中一次获取一个元素。您已将文件的内容读入单个字符串,因此 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:
    ....

【讨论】:

    猜你喜欢
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 2018-03-02
    • 2014-08-23
    • 2020-01-29
    相关资源
    最近更新 更多