首页 \ 问答 \ 正则表达式,用于在未注释掉的标签之间查找文本(Regular Expression to find text between tags that are not commented out)

正则表达式,用于在未注释掉的标签之间查找文本(Regular Expression to find text between tags that are not commented out)

我有一个简单的场景似乎在困扰我。 我想在两个没有注释掉的标签之间得到文本。 这是一个例子:

// Example of commented text
// :Start
// <I don't want to get this text>
// :End


:Start
<Here is the text i want>
:End

解:

感谢大家的帮助。 超快地收到答案,完全符合我的需要。 我选择了以下正则表达式,因为它最适合我的情况。 特别感谢Tim Pietzcker:

(?sm)(?<=^:Start\s*)(?:(?!^:End).)*

I have a simple scenario that seems to be stumping me. I want to get the text between two tags which are not commented out. Here is an example:

// Example of commented text
// :Start
// <I don't want to get this text>
// :End


:Start
<Here is the text i want>
:End

Solution:

Thanks to all for your help. Received the answer super fast and does exactly what I need. I went with the following regular expression because it worked best for my situation. Special thanks to Tim Pietzcker:

(?sm)(?<=^:Start\s*)(?:(?!^:End).)*

原文:https://stackoverflow.com/questions/12804865
更新时间:2023-10-23 14:10

最满意答案

你可以检查文件是否已经存在,然后不要调用writeheader()因为你打开带有附加选项的文件。

类似的东西:

import os.path


file_exists = os.path.isfile(filename)

with open (filename, 'a') as csvfile:
    headers = ['TimeStamp', 'light', 'Proximity']
    writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=headers)

    if not file_exists:
        writer.writeheader()  # file doesn't exist yet, write a header

    writer.writerow({'TimeStamp': dic['ts'], 'light': dic['light'], 'Proximity': dic['prox']})

You could check if file is already exists and then don't call writeheader() since you're opening the file with an append option.

Something like that:

import os.path


file_exists = os.path.isfile(filename)

with open (filename, 'a') as csvfile:
    headers = ['TimeStamp', 'light', 'Proximity']
    writer = csv.DictWriter(csvfile, delimiter=',', lineterminator='\n',fieldnames=headers)

    if not file_exists:
        writer.writeheader()  # file doesn't exist yet, write a header

    writer.writerow({'TimeStamp': dic['ts'], 'light': dic['light'], 'Proximity': dic['prox']})

相关问答

更多
  • 简答:不 长答案:这取决于 使用CSV编写器完全可以追加数据。 只需在"a"模式下打开文件即可: with file("data.csv", "a" as fh: w = csvwriter(fh): w.writerow(...) 编辑CSV文件并不那么简单,因为除非您正在编辑的列是固定长度的,否则您需要插入和删除部分文件。 csv模块没有内置的方法。 您可以打开原始文件,删除(或重命名原始文件)并打开一个具有相同名称的新文件: with file("data.csv", "r") as ...
  • 根本不需要使用DictWriter: import csv import numpy as np data1 = np.arange(10) data2 = np.arange(10)*2 data3 = np.arange(10)*3 writefile = '../test.csv' fieldnames = ['data1','data2', 'data3'] with open( writefile, 'w' ) as f: writer = csv.writer(f) writ ...
  • 只需使用一个标志: headers_written = False 然后在写行时: if not headers_written: writer.writerow(headers) headers_written = True writer.writerow(somerow) 实际上你推迟创建编写器,直到你确定你有写东西为止: writer = None # ... if not writer: writer = csv.writer(open(filename, 'wb' ...
  • 看起来您想要将列的子集写入新文件。 使用DictReader / DictWriter这个问题更简单。 注意使用Python 3.x时正确使用open 。 您的尝试是使用Python 2.x方式。 import csv # headers you want in the order you want headers = ['header1','header5','header6','header7'] with open('write.csv','w',newline='') as csvWriter, ...
  • 在第一个循环中,每个字符串都放入result列表的单独元素中,因此它不是行列表。 你应该改变这个循环来使用: result.append([row[0], row[10], row[11]]) 将这些字段附加为每行的列表。 在第二个循环中,您使用的是csv.writer ,因此它将添加分隔符,并且不应使用format 。 写吧: fwriter.writerow(row) 如果您希望字段分隔符为:在输出文件中,请使用: fwriter=csv.writer(f,":") In the first lo ...
  • 您可以使用python CSV的csv.writer的作家,如下所示: def export_as_csv(modeladmin, request, queryset): headers, fields = zip(*export_info_trial) headers_participant, fields_participant = zip(*export_info_participant) zipFile = ZipFile(in_memory, 'w') rows = ...
  • 你可以检查文件是否已经存在,然后不要调用writeheader()因为你打开带有附加选项的文件。 类似的东西: import os.path file_exists = os.path.isfile(filename) with open (filename, 'a') as csvfile: headers = ['TimeStamp', 'light', 'Proximity'] writer = csv.DictWriter(csvfile, delimiter=',', lin ...
  • DictReader的第一个参数应该是一个文件对象(用open()创建),参见。 http://docs.python.org/py3k/library/csv.html#csv.DictReader 您忘记了TEMPLATE文件的open() 。 import csv file_name = "test.tsv" TEMPLATE = "template.tsv" fil = open(file_name, "w") # you forgot this line, which will open th ...
  • 执行查询后,您可以执行此操作: columns = [i[0] for i in cursor.description] 所以你得到 query = """select * from """ .format(line_name) tmp = cursor.execute(query) columns = [i[0] for i in cursor.description] results = tmp.fetchall() 然后做: if results: myFile = csv.writer( ...
  • 这里缺少一条关键信息:什么是dictToSearch? 我想这就像{'e2fc714c4727ee9395f324cd2e7f331f':'abcd','098f6bcd4621d373cade4e832627b4f6':'test'}。 如果是这样,这里的问题是“for d in dictToSearch”将n设置为dictToSearch的第一个键 - 这将是一个MD5哈希。 然后,writerow(n)将MD5哈希字符串解释为本身由单字符键和值组成的字典,而不是字符串。 我怀疑你真正想做的是: for ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。