Domanda

So I have this code:

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)

When I print words, it prints the words in the dictionary, one word at a time, which is great. But as soon as I try and do anything with those words like in my last two lines, it automatically separates the words into letters, and prints one letter per line of each word. Is there anyway to keep the words together? My end goal is to do ordered=sorted(line), and then an if (ordered==unscrambled) have it print the original word from the dictionary?

È stato utile?

Soluzione

Your words is an instance of str. You should use split to iterate over words:

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

Altri suggerimenti

A for-loop takes one element at a time from the "sequence" you pass it. You have read the contents of your file into a single string, so python treats it as a sequence of letters. What you need is to convert it into a list yourself: Split it into a list of strings that are as large as you like:

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

Or

wordlist = words.split()    # Makes a list of "words", by splitting at whitespace
for word in wordlist:
    ....
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top