删除导入的文本文件(Python)

时间:2017-12-02 23:07:41

标签: python string file kindle

我正在尝试从我从Kindle导入的文本文件中删除几行。文字如下:

Shall I come to you?
Nicholls David, One Day, loc. 876-876


Dexter looked up at the window of the flat where Emma used to live.
Nicholls David, One Day, loc. 883-884


I want to grab the bin bag and do a forensics
Sophie Kinsella, I've Got Your Number, loc. 64-64

完整的文件更长,这只是一个文件。我的代码的目的是删除写入“loc。”的所有行,以便只保留提取。我的目标也可以看作是删除空白行之前的行。

到目前为止,我的代码如下所示:

f = open('clippings_export.txt','r', encoding='utf-8')
message = f.read()
line=message[0:400]
f.close()

key=["l","o","c","."," "]


for i in range(0,len(line)-5):
    if line[i]==key[0]:
        if line[i+1]==key[1]:
            if line[i + 2]==key[2]:
                if line[i + 3]==key[3]:
                    if line[i + 4]==key[4]:

最后if找到每个“loc。”位于文件中的位置(索引)。然而,在这个阶段之后,我不知道如何回到行中,以便代码捕获行开始的位置,并且可以完全删除。我接下来该怎么办?你建议我用另一种方法删除这一行吗?

提前致谢!

1 个答案:

答案 0 :(得分:3)

我认为这个问题可能有点误导!

无论如何,如果您只想删除这些行,则需要检查它们是否包含“loc”。子。可能最简单的方法是使用in operator

不是从 read()函数获取整个文件,而是逐行读取文件(例如,使用readlines() function)。然后,您可以检查它是否包含您的密钥,如果有,则将其省略。

由于结果现在是字符串列表,您可能希望将其合并:str.join()

这里我使用了另一个列表来存储所需的行,你也可以使用“更多pythonic”filter()或列表理解(我在下面提到的类似问题中的例子)。

f = open('clippings_export.txt','r', encoding='utf-8')
lines = f.readlines()
f.close()

filtered_lines = []
for line in lines:
    if "loc." in line: 
        continue
    else:
        filtered_lines.append(line)

result = ""
result = result.join(filtered_lines)

顺便说一句,我认为它可能是重复的 - Here's question about the opposite(想要包含密钥的行)。