How to make this get all words in the file

Question:

So I have been trying to make a programming language very simply and I encountered something I can’t do. I’m trying to see if every word in a file has this text in it but I don’t know how to get every word. Any help would be greatly appreciated.

with open("hello.dita","r") as f:
    for line in f:
        if line.split().pop(0)) == "print":
            if line.split().pop(1) == "-s":
                print(line.split().pop(2))

hello.dita contains:

print -s hello print -s this works?

and its outputs:

hello

Asked By: Albi

||

Answers:

If I understand the question, you want to recognise a line with the format print -s text and print the text. Your error here is that pop index by default is -1, so this code will work:

with open("hello.dita", "r") as f:
    for line in f:
        if line.split().pop(0) == "print":
            if line.split().pop(1) == "-s":
                print(line.split().pop(2))

But you can do some upgrades for improve the performance, like store the splitted string in a variable to avoid repitting the same split, and use the [] instead of pop to avoid list modification:

with open("hello.dita", "r") as f:
    for line in f:
        arguments = line.split()
        if arguments[0] == "print":
            if arguments[1] == "-s":
                print(arguments[2])

Another possible error, is that your code will fail for a line like print or print -s, so you should check the list length:

with open("hello.dita", "r") as f:
    for line in f:
        arguments = line.split()
        if len(arguments) >= 1 and arguments[0] == "print":
            if len(arguments) >= 3 and arguments[1] == "-s":
                print(arguments[2])

And at least, if you want that the text can contain white spaces, you can do:

with open("hello.dita", "r") as f:
    for line in f:
        arguments = line.split()
        if len(arguments) >= 1 and arguments[0] == "print":
            if len(arguments) >= 3 and arguments[1] == "-s":
                print(' '.join(arguments[2:]))
Answered By: Rodrigo Llanes
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.