Python:在文件中查找一行与windows兼容,但不适用于linux

时间:2016-03-18 02:37:00

标签: python linux windows python-2.7 dictionary

我正在尝试创建一段充当字典的代码。这是一个更大的项目的一部分,但似乎工作正常(目前......)。我让它在Windows 10上工作,但是一旦我换到我的Ubuntu机器(我将运行该程序的终端机器),它就停止使用我提供的文件了。下面是我的代码,这个有点乐趣。

def commandDefineWord(request):         # NOT WORKING
    vanillaRequest = request.split(' ')
    clearRequest = (request.lower()).split(' ');

    if ((clearRequest[0] == "what") and (clearRequest[1] == "is") and (clearRequest[2] == "the")
        and (clearRequest[3] == "definition") and (clearRequest[4] == "for")):
        del clearRequest[0];
        del vanillaRequest[0];
        del clearRequest[0];
        del vanillaRequest[0];
        del clearRequest[0];
        del vanillaRequest[0];
        del clearRequest[0];
        del vanillaRequest[0];      # Lots of extra word screening
        del clearRequest[0];
        del vanillaRequest[0];
    if (clearRequest[0] == "define"):
        del clearRequest[0];
        del vanillaRequest[0];
    if ((clearRequest[0] == "the") and (clearRequest[1] == "word")):
        del clearRequest[0];
        del vanillaRequest[0];
        del clearRequest[0];
        del vanillaRequest[0];

    word = (vanillaRequest[0]).upper(); # define the word as a variable
    word = word.replace("?", "");       # remove ?'s
    dictionary = open("dictionary.txt", "r");   # Open dictionary file
    searchLines = dictionary.readlines();   # create a readable copy
    dictionary.close(); # Close file for safety

    found = False       # set as precaution to not finding word
    for i, line in enumerate(searchLines):  # enumerating all the lines while making them individual
        if (("%s\n" % word) == line):   # where is the bloody word?
            found = True;   # word is found
            print searchLines[i];   # print result
            i+=1;   # go to next line of definition
            while not searchLines[i].isupper(): # check to see if defintion end is reached
                searchLines[i] = searchLines[i].replace("\n", "");  # take away new lines
                print "\t %s" % searchLines[i]; # prints defintion
                i += 1;
    if found == False:
        print "Sorry, I could not find a definition for %s." % word

使用了vanillaRequest和clearRequest位,因为(尽管我付出了最大努力)我的大脑告诉我这样做与我写的其他函数类似。这对于这个特定功能来说不是必需的,但在其他功能中,我必须保留原始请求。

给出了一些可能重要的信息,我正在使用的词典文本是#34; Webster的Unabridged Dictionary"来自古腾堡项目。我很抱歉不知道如何上传这个文件(希望你能找到它)。

问题似乎(对我来说)源于" if(("%s \ n"%word)== line):"。我不知道是什么原因导致它在Windows上工作但不是Linux,但我可以提供一些有用的信息。我创建了一个只有这些行的虚拟字典:

HELL

test definition

HECK

它就像在Windows上一样工作。我认为问题出在档案上,但我找不到。我是否应该遗漏任何重要的,神秘的解决信息,请在评论中告诉我,我会尽快添加(如果可以的话)!

如果有人能提供任何见解,我们将不胜感激。谢谢!

P.S。是的,代码有点笨拙,有点像眼睛。我不打算改变它,因为它的工作原理完全正常(除了整个" Linux不想用我的文件和#34;困境。

1 个答案:

答案 0 :(得分:0)

我只是测试一下,在if (("%s\n" % word) == line):代码之前,打印wordline变量,word总是大写字符,而line不是这样。也许这就是if陈述不起作用的原因。