簡體   English   中英

匹配txt文件中的每個單詞

[英]Matching every word in a txt file

我正在研究歐拉計畫問題(很有趣)。 它帶有一個46kb的 txt文件,其中包含1行,其中包含5000多個名稱的列表,格式如下:

"MARIA","SUSAN","ANGELA","JACK"...

我的計划是編寫一種方法來提取每個名稱並將其附加到Python列表中。 正則表達式是解決此問題的最佳武器嗎?
我查找了Python re doc,但是很難找出正確的正則表達式。

看起來像csv模塊會有用的格式。 然后,您不必編寫任何正則表達式。

如果文件的格式如您所說,即

  1. 這是一行
  2. 格式如下:“ MARIA”,“ SUSAN”,“ ANGELA”,“ JACK”

然后這應該工作:

 >>> import csv >>> lines = csv.reader(open('words.txt', 'r'), delimiter=',') >>> words = lines.next() >>> words ['MARIA', 'SUSAN', 'ANGELA', 'JACK'] 

正則表達式可以完成工作,但是效率很低。 使用csv可以工作,但可能無法很好地在一行中處理5000個單元。 至少它必須加載整個文件並在內存中維護整個名稱列表(這對您來說可能不是問題,因為這是非常少量的數據)。 如果要使用相對較大的文件(遠大於5000個名稱)的迭代器,則狀態機可以解決問題:

def parse_chunks(iter, quote='"', delim=',', escape='\\'):
    in_quote = False
    in_escaped = False

    buffer = ''

    for chunk in iter:
        for byte in chunk:
            if in_escaped:
                # Done with the escape char, add it to the buffer
                buffer += byte
                in_escaped = False            
            elif byte == escape:
                # The next charachter will be added literally and not parsed
                in_escaped = True          
            elif in_quote:
                if byte == quote:
                    in_quote = False
                else:
                    buffer += byte
            elif byte == quote:
                in_quote = True
            elif byte in (' ', '\n', '\t', '\r'):
                # Ignore whitespace outside of quotes
                pass
            elif byte == delim:
                # Done with this block of text
                yield buffer
                buffer = ''                    
            else:
                buffer += byte

    if in_quote:
        raise ValueError('Found unbalanced quote char %r' % quote)
    elif in_escaped:
        raise ValueError('Found unbalanced escape char %r' % escape)

    # Yield the last bit in the buffer
    yield buffer

data = r"""
"MARIA","SUSAN",
"ANG
ELA","JACK",,TED,"JOE\""
"""
print list(parse_chunks(data))

# ['MARIA', 'SUSAN', 'ANG\nELA', 'JACK', '', 'TED', 'JOE"']

# Use a fixed buffer size if you know the file has only one long line or
# don't care about line parsing
buffer_size = 4096
with open('myfile.txt', 'r', buffer_size) as file:
    for name in parse_chunks(file):
        print name

如果您可以簡化它,那么就可以簡化它。 無需使用csv模塊。 我認為5000個名稱或46KB不足以擔心。

names = []
f = open("names.txt", "r")

# In case there is more than one line...
for line in f.readlines():
    names = [x.strip().replace('"', '') for x in line.split(",")]

print names
#should print ['name1', ... , ...]

暫無
暫無

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

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