0

所以我知道设置点<start point><end point>文本文件,我需要使用它们来查找它们之间的某些信息,这些信息将被使用和打印。我目前有.readlines()一个不同的功能,用于在新功能中查找信息。

4

2 回答 2

1

你可以尝试这样的事情:

flag = False
info = [] # your desired information will be appended as a string in list
with open(your_file, 'r') as file:
   for line in file.readlines():
       if '<start point>' in line: # Pointer reached the start point
           flag = True
       if '<end point>' in line: # Pointer reached the end point
           flag = False
       if flag:  # this line is between the start point and endpoint
           info.append(line)

>> info
['Number=12', 'Word=Hello']
于 2018-05-12T11:59:59.930 回答
0

这似乎是正则表达式的工作。如果您还没有遇到过正则表达式,它们是一个非常强大的工具,基本上可以用来搜索文本字符串中的特定模式。

例如,正则表达式(或简称 regex)Number=\d+会在文本文档中找到Number=后跟任意数量的数字字符的任何行。正则表达式Word=\w+将匹配任何Word=以字母开头然后后跟任意数量的字母的字符串。

在 python 中,您可以通过re 模块使用正则表达式。有关在 python 中使用正则表达式的精彩介绍,请查看《用 Python 自动化无聊的东西》一书中的这一章。要测试正则表达式,这个站点很棒。

在这种特殊情况下,您将执行以下操作:

import re
your_file = "test.txt"
with open(your_file,'r') as file:
    file_contents = file.read()
number_regex = re.compile(r'Number=\d+')
number_matches = re.findall(number_regex, file_contents)

print(number_matches)
>>> ['Number=12']

这将返回一个列表,其中包含与数字正则表达式的所有匹配项。然后你可以对单词匹配做同样的事情。

于 2018-05-12T12:33:20.127 回答