python
  • regex
  • grep
  • 2015-08-20 55 views 1 likes 
    1

    第一次發佈和一點菜鳥,所以如果任何禮儀或格式問題,然後讓我知道。爲什麼grep在文件中找不到字符串?

    我試圖在文件(圖像下面)上使用grep函數來檢查文件中是否存在單詞。當我查看文件時,這個詞絕對存在。它被空間包圍,並且是一行中的最後一個詞。

    由於某種原因,grep無法找到該單詞,程序返回0.爲什麼?

    謝謝!

    import os 
    import re 
    
    word = "aliows" 
    folder = '/Users/jordanfreedman/Thinkful/Projects/Spam_Filter/enron1/spam/' 
    email = '4201.2005-04-05.GP.spam.txt' 
    
    number = int(os.popen("grep -w -i -l " + word + " " + folder + email + " | wc -l").read()) 
    print number 
    
    +0

    你只是想獲得'word'出現在文本文件中的次數嗎? – IanAuld

    +0

    當你在命令行上運行'grep'命令時會發生什麼? – MattDMo

    +0

    如果您在shell中手動運行該命令,它是否工作?你可以''grep'爲該行上的其他內容並將輸出傳遞給'xxd'或'hexdump'? –

    回答

    -1

    您需要發佈該文件的片段,以便我們可以測試grep語句。此外,沒有理由掏出:

    import re 
    
    word = "aliows" 
    folder = '/Users/jordanfreedman/Thinkful/Projects/Spam_Filter/enron1/spam/' 
    email = '4201.2005-04-05.GP.spam.txt' 
    
    file = folder + email 
    fh = open(file, 'r') 
    
    contents = re.findall(word, fh.read()) 
    
    print(len(contents)) 
    
    +0

    我認爲這可行 - 謝謝!讓我試試它在我的主程序(循環遍歷所有文件)... –

    +0

    代碼將'word'視爲可能不合意的正則表達式。你還沒有實現'-w'(匹配字邊界),'-l'(提前退出),'-i'(忽略大小寫)。不需要一次將整個文件加載到內存中。 – jfs

    0

    你可以找出是否存在使用退出狀態匹配:

    import os 
    from subprocess import STDOUT, call 
    
    path = os.path.join(folder, email) 
    with open(os.devnull, 'wb', 0) as devnull: 
        rc = call(['grep', '-w', '-l', '-i', '-F', word, path], 
          stdout=devnull, stderr=STDOUT) 
    if rc == 0: 
        print('found') 
    elif rc == 1: 
        print('not found') 
    else: 
        print('error') 
    

    或者as @stevieb mentioned,你能找到的單詞是否是在給定的在純Python中的文件:

    import re 
    from contextlib import closing 
    from mmap import ACCESS_READ, mmap 
    
    with open(path) as f, closing(mmap(f.fileno(), 0, access=ACCESS_READ)) as m: 
        if re.search(br"(?i)\b%s\b" % re.escape(word), m): 
         print('found') 
    
    相關問題