簡體   English   中英

讀取文件時,Python提取單個字符串

[英]Python pull individual strings when reading a file

我是Python的新手。 我正在通過一個讀取文件的示例進行研究,並且已經研究了一段時間,但無法弄清楚我在做什么錯。 我想做的是遵循與從源文件中搜索字符串以查看其是否存在於目標文件中相同的邏輯。 考慮一下,我的源文件是字符串字典,目標文件是要搜索字符串的數據文件。 這似乎可行,但是我現在想要做的是一次將每個字符串傳遞給一個名為diff的自定義模塊,以比較這些字符串。 現在發生的是,由於我傳遞的是字符串列表,而不是一次傳遞一個字符串,因此結果被丟棄了。 我如何一次將字符串傳遞給下面的diff命令。

with open('./dic') as f:
    dictionary = f.read()

if not dictionary:
    sys.exit("Could not read dictionary data :-(")

with open('./dat') as f:
    for dataFile in (line.strip() for line in f):
        print 'dataFile: ', dataFile
        print 'dictionary: ', dictionary
        score=diff.dataL(dataFile, dictionary)
        print 'Diff score: ', score

例如,我的輸出看起來像這樣-您可以看到它每次為字典傳遞3個項目,而不是1個。

dataFile:  aaaa
dictionary:  aaaa
bbbb
cccc

dataFile:  test test
dictionary:  aaaa
bbbb
cccc

dataFile:  fail fail
dictionary:  aaaa
bbbb
cccc

謝謝您的幫助!

您的可變字典實際上是一個字符串,因此從技術上講它是一項。 如果要使其成為列表,例如要進行迭代,則可以執行以下操作:

dictionary_list = dictionary.split()

這將使“字符串”字典中由空格分隔的每個字符串成為列表dictionary_list中的一個項目。

對於此行:

dictionary = f.read()

您想使用readlines方法返回列表中的所有行

不是以字符串形式返回所有文件內容的read方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM