简体   繁体   English

如何使它获取文件中的所有单词

[英]How to make this get all words in the file

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: hello.dita 包含:

print -s hello print -s this works?

and its outputs:及其输出:

hello

If I understand the question, you want to recognise a line with the format print -s text and print the text.如果我理解这个问题,您想识别格式为print -s text的行并打印文本。 Your error here is that pop index by default is -1, so this code will work:您的错误是默认情况下弹出索引为-1,因此此代码将起作用:

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:但是您可以进行一些升级以提高性能,例如将拆分的字符串存储在变量中以避免重复相同的拆分,并使用 [] 而不是 pop 以避免修改列表:

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:另一个可能的错误是,您的代码对于printprint -s之类的行将失败,因此您应该检查列表长度:

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:]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM