从大文件读取字符串

2024-04-18 21:41:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很大的文本文件(parsed.txt),其中包含了将近150万行。每行的格式如下:

foobar foo[Noun]+lAr[A3pl]+[Pnon]+[Nom]
loremipsum lorem[A1sg]+lAr[A3pl]+[Pl]+[Nom]

我在空格后给出第二个字段,用这个函数得到空格前的第一个字段:

def find_postag(word,postag):
    with open('parsed.txt',"r") as zemberek:    
        for line in zemberek:
            if all(i in line for i in (word,postag)):
                if line.split(" ")[0].startswith(word) and line.split(" ")[1] == word+postag:
                    selectedword = line.split(" ")[0]
                    break
        return selectedword

但是,它工作得太慢了。我不知道怎样才能使这个过程更快。我的想法是:parsed.txt文件是按字母顺序排列的。如果给定的word变量以“z”字母开头,则不必要地读取近900.000行。如果从第900.000行检查给定的word以“z”字母开头,可能会更快。有没有更好的办法,我如何实施?你知道吗


Tags: intxtforif字母lineparsednom
1条回答
网友
1楼 · 发布于 2024-04-18 21:41:35

因为您的输入文件是按字母顺序排列的,所以您可以创建一个字典,其中包含每个字母开头的行号,如下所示:

with open('parsed.txt', 'r') as f:
    data = [line.strip() for line in f if line.strip()]

index = dict()
for i in range(len(data)):
    line = data[i]
    first_letter = line[0].lower()
    if first_letter not in index:
        index[first_letter] = i

您可能希望在开始时添加该代码,以便在开始执行搜索之前它只运行一次。这样,当你搜索一个单词时,你可以让它开始搜索它的第一个字母开始的位置,如下所示:

def find_postag(word, postag):
    start = index[word[0].lower()]
    for line in data[start:]:
        # your code here
        if all(i in line for i in (word,postag)):
            if line.split(" ")[0].startswith(word) and line.split(" ")[1] == word+postag:
                selectedword = line.split(" ")[0]
                break
    return selectedword

相关问题 更多 >