python - 如何从文本文件中提取特定文本
问题描述
你好 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
解决方案
您可以使用正则表达式,因此类似于此
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.
)
推荐阅读
- maven - 使用 Selenium-Cucumber Maven 在每次运行时创建单独的报告目录
- php - 将附件路径推送到数据库表
- ms-access - 当通过另一个表格输入信息时,更新表格中的表格信息
- r - R - 像 excel 这样的计数
- python-3.x - 使用 PyNER 的斯坦福名称实体识别器(NER)不起作用
- batch-file - 如何在命令提示符下使用 CD 命令更改为仅以空格命名的文件夹?
- c# - 在 C# 中,如何使用正则表达式扫描非常大的文件 - 或者是否可以一次提供一个正则表达式一个字符?
- python - 从 discord.py rewrite 发送一个 pm
- c - 如何从 C 中的字符串中打印出所有其他字符?
- angular - 隐藏 Highstocks 滚动条内的折线图