如何每3行删除一行

时间:2019-11-08 16:30:25

标签: python python-3.x

我正在寻找使用python在文本文件中每3行删除一行。 我正在使用的文本文件遵循以下模式:

["न", "म", "स्", "ते"]

以下几行文件可以更好地理解:

First line is the Name of the sender

Second is the Message sent 

Third one is the Date the message was sent(ex : 8 nov. 2019 à 14:29)

我已经清理了文件使其遵循这种模式,因此现在我尝试删除带有日期的每一行。

首先,我想删除每行以数字开头的行,但有些消息以数字开头,因此这不是正确的路径。 在这种情况下,删除3的倍数的行将不起作用。

您对如何读取文件并在没有日期行的情况下编写另一个文件有一些想法吗?

谢谢

编辑:谢谢,我有一个很好的答案,确实有很多方法可以解决编程中的问题。谢谢您的宝贵时间!

6 个答案:

答案 0 :(得分:2)

好吧,假设我有像您输入的行的列表:

>>> lines
['Name (2 participants)', 'Message', 'Date (ex : 8 nov. 2019 à 14:29)']

不能让您执行以下操作吗?

>>> regex = re.compile("Date \(")
>>> [line for line in lines if not regex.match(line)]
['Name (2 participants)', 'Message']

之所以可行,是因为re.match仅从行首开始匹配。

任何以Date (开头的行都会被跳过

答案 1 :(得分:0)

为什么删除三行之三的行会不起作用?

否则,您可以执行以下操作:

对于文本文件中的每一行,请检查前几个字符是否为“日期”,如果为true,则删除该行。

(如果您仍然看不到我的建议,我可以编辑答案以添加一些代码)

编辑:

好吧,因此不清楚“日期行”不是以字符串“日期”开头。但是,如果您知道日期的正则表达式(在regex中转换为2019年11月8日或2018年10月5日),则可以检查每一行以查看正则表达式并相应地将其删除。

答案 2 :(得分:0)

select, join and dropDuplicates

屈服

rewrite_srt = ''

# Read the file with date
with open('x.txt', 'r') as f_read:
    for line in f_read:
        if not line.startswith('Date'):
             rewrite_srt += line


# Write the new file without date

with open('y.txt', 'w') as f_write:
     f_write.write(rewrite_srt)

跳过每X行:

Name (2 participants)

Message

屈服

rewrite_srt = ''
count = 0
skip_each = 5

# Read the file with date
with open('x.txt', 'r') as f_read:
    for line in f_read:
        count +=1
        if count == skip_each:
             count = 0
        else:
             rewrite_srt += line


# Write the new file without date

with open('y.txt', 'w') as f_write:
     f_write.write(rewrite_srt)

答案 3 :(得分:0)

由于“à”在该行中很常见,请执行以下操作:

   with open("filename.txt", "r") as f:
        lines = f.readlines()
    with open("filename.txt", "w") as f:
       for line in lines:
        if 'à' not in line:
            f.write(line)

答案 4 :(得分:0)

如果文件每条消息始终有三行,则需要这样的内容:

from itertools import groupby

all_messages = []
with open("messages.txt", "r") as in_file:
    for line_num, line in enumerate(in_file):
        if line_num % 3 == 0: # First line of every three
            participant = line.strip()
        elif line_num % 3 == 1: # Second line of every three
            content = line.strip()
        elif line_num % 3 == 2: # Third line of every three
            all_messages.append((participant, content))

all_messages.sort(key=lambda message: message[0]) # Messages must be sorted for groupby
for participant, messages in groupby(all_messages, lambda message: message[0]):
    with open(f"{participant}.txt", "w") as out_file:
        for message in messages:
            out_file.write(f"{message[1]}\n") # Include newline

答案 5 :(得分:-1)

此功能将删除包含目标的所有行,并写入一个新文件:

import re

def file_read_and_write_B(FILE1, FILE2):
   """copies file1 to file2 excluding lines that match a regex"""
   #Use Nathan McCoy answer above with more complex regex:
   regex = re.compile(r"^[0-9]+ [a-z]+\. [0-9]+")
   with open(FILE, 'r') as fdin:
       with open(FILE2, 'w') as fdout:
           for line in fdin:
               line = line.strip()   #remove trailing/leading whitespace
               if not regex.search(line):   #skips lines that match
                   print(line, file=fdout)              

此正则表达式可以改进,但它将匹配以“ 2019年6月12日”开头的行(也可以匹配以“ 1234 a。1”开头的行)。

编辑:这种方法不会消耗太多内存,因为您一次只能读取一行。与其他功能进行比较:

def read_store_process_write(FILE1, FILE2):
    with open(FILE1, 'r') as fdin:
        temp = fdin.readlines()        #stores all lines in a file to a list
    regex = re.compile(r"^[0-9]+ [a-z]+\. [0-9]+")
    result = [x for x in temp if not regex.search(x)]  #new list w/o matches
    with open(FILE2, 'w') as fdout:
        fdout.writelines(result)

这种方法的问题是,如果要处理的文件很大,则会用完内存。