首页 > 解决方案 > 如何从文本文件中提取特定文本

问题描述

你好 Stackoverflow 社区,

我的代码有问题,我试图从文本文件中检索一些特定的文本,我可以做到。但我正在使用 seek 方法来检索数据。但为此,我给出了文本的起始位置和文本的结束位置。这给了我想要的确切输出。但有时检索文本的长度可能会更长,然后我的代码无法检索整个文本。那我该怎么做

我正在使用 python2.7 并尝试从文本文件中检索特定数据

file = open("C:\Users\This_PC\p4.txt", "r")
file.seek(645)
string = file.read(13 - 0)
print string

我按预期得到了输出test_label123。但是在文本文件中,如果文本的长度较长,test_label12345那么我得到的输出test_label123是错误的。

p4.txt 内容在下面提到

# A Perforce Label Specification.
#
#  Label:       The label name.
#  Update:      The date this specification was last modified.
#  Access:      The date of the last 'labelsync' on this label.
#  Owner:       The user who created this label.
#  Description: A short description of the label (optional).
#  Options:     Label update options: [un]locked, [no]autoreload.
#  Revision:    Optional revision specification to make an automatic label.
#  ServerID:    If set, restricts access to the named server.
#  View:        Lines to select depot files for the label.
#
# Use 'p4 help label' to see more about label views.

Label:  test_label123

Owner:  This_PC

Description:
    Created by Auto12

Options:    unlocked noautoreload

标签: pythonpython-2.7

解决方案


您可以使用正则表达式,因此类似于此

import re

file = open("test.txt", "r")
string = file.read()
m = re.search('(?<=Label:) {0,2}(\w+)', string)

print m.group(1)

您可能需要调整您的正则表达式以正确读取第二个外观而不是第一个 ( Label: The label name.)


推荐阅读