Python批量提取txt文件中的特定字符后的数字?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python批量提取txt文件中的特定字符后的数字?相关的知识,希望对你有一定的参考价值。
数据如图,自己参照csdn上的代码改了一下,不过跑不出结果。
2、待读取文件
是以":"作为分隔符的数据,每一行以回车结束。此文件为XXX.train
3、读取每一句中的汉字
1234567891011...file_train = os.path.join(rootDir,"data/train/rg_train_"+modle_date+"_"+aiscene+".train")with open(file_train, 'r')as fp: textlist = fp.readlines() for text in textlist: if ":" in text: L4ID = text.split(":")[-2] Msg = text.split(":")[-1] if query_start == Msg.strip("\\n"): print("Msg is in train:",Msg)...
代码中先获取文件,然后读取每一行,然后以":"作为分隔符。(-1代表倒数第一个,-2代表倒数第二个)
不管是txt文件还是xml文件还是其他的,都可以用这种方法来批量替换文件中字符串:
1234567891011121314151617# -*- coding:utf-8 -*-__author__ = 'ShawDa' import glob xmls = glob.glob('xml_files/*.xml')for one_xml in xmls: print(one_xml) f = open(one_xml, 'r+', encoding='utf-8') all_the_lines = f.readlines() f.seek(0) f.truncate() for line in all_the_lines: line = line.replace('dog', 'pig') line = line.replace('cat', 'bike') f.write(line) f.close()
参考技术A 第16行,'a'应该改成a追问
我之前也试过用a还是会报错
![](https://image.cha138.com/20230512/a5e0aa55dc39418bb4cfced10508f3df.jpg)
第14行,rb改成r
追问果然如此多谢啦!
那假如我要提取这个元素后一个如何实现呢?能指条路吗?
本回答被提问者采纳从 Python3 中的 zip 存档中提取特定文件夹的内容
【中文标题】从 Python3 中的 zip 存档中提取特定文件夹的内容【英文标题】:Extract the content of a specific folder from a zip archive in Python3 【发布时间】:2020-02-19 12:58:21 【问题描述】:我有一个 zip 存档,其内部结构如下所示:
file.zip
|
--- foo/
|
--- bar/
|
--- file1.txt
|
--- dir/
|
--- file2.txt
我想使用 python3 将bar
的内容提取到输出目录,得到如下所示的内容:
output-dir/
|
--- file1.txt
|
--- dir/
|
--- file2.txt
但是,当我在bar
下面运行代码时,它的内容被提取到output-dir
import zipfile
archive = zipfile.ZipFile('path/to/file.zip')
for archive_item in archive.namelist():
if archive_item.startswith('bar/'):
archive.extract(archive_item, 'path/to/output-dir')
我该如何解决这个问题? 谢谢!
【问题讨论】:
不是真正的解决方案,而是一种规避问题的方法:解压到path/to
,得到path/to/bar
,然后将path/to/bar
重命名为path/to/output-dir
。
更改archive_item.startswith('file/bar/')
会给出bar目录内容
【参考方案1】:
不要使用ZipFile.extract
,而是使用ZipFile.open
、open
和shutil.copyfileobj
以便将文件准确地放在您想要的位置,使用路径操作来创建输出你需要的路径。
archive = zipfile.ZipFile('path/to/file.zip')
PREFIX = 'bar/'
out = pathlib.Path('path/to/output-dir')
for archive_item in archive.namelist():
if archive_item.startswith(PREFIX):
# strip out the leading prefix then join to `out`, note that you
# may want to add some securing against path traversal if the zip
# file comes from an untrusted source
destpath = out.joinpath(archive_item[len(PREFIX):])
# make sure destination directory exists otherwise `open` will fail
os.makedirs(destpath.parent, exist_ok=True)
with archive.open(archive_item) as source,
open(destpath, 'wb') as dest:
shutil.copyfileobj(source, dest)
类似的东西。
【讨论】:
我建议把4
改成len('bar/')
,这样更容易修改。以上是关于Python批量提取txt文件中的特定字符后的数字?的主要内容,如果未能解决你的问题,请参考以下文章
Python数据处理 | 批量提取文件夹下的csv文件,每个csv文件根据列索引提取特定几列,并将提取后的数据保存到新建的一个文件夹
Python数据处理 | 批量提取文件夹下的csv文件,每个csv文件根据列索引提取特定几列,并将提取后的数据保存到新建的一个文件夹