![](/img/trans.png)
[英]How to retrieve the last 5 characters from dictionary value after converting to string
[英]Retrieve value after a specfic string of characters
我正在尝试从特定字符串之后的一行中提取一个值。
文本文件行如下:
directory, batch: xxx Date: xxxxxx xx:xx Pulp: type
AAAAAAAA
bbbbbbbb
cccccccc
dddddddd
eeeeeeee
我需要在列表output[f]
添加'Pulp:type'并添加该行。 组成果肉类型的字符数量在3-25个字符之间。
这是我目前拥有的:
for f in file_list:
txtfile = open(f, 'r')
output[f] = []
for line in txtfile:
if 'batch' in line: #only identifier for line is 'batch'
# What Goes Here??
for i,line in enumerate(txtfile):
if i == 4:
output[f].append(line)
elif i == 5:
output[f].append(line)
我不知道如何从生产线上提取我需要的东西。 有任何想法吗?
使用正则表达式:
import re
a = "directory, batch: xxx Date: xxxxxx xx:xx Pulp: type"
m = re.match('.+(Pulp.+$)', a)
my_type_string = m[1]
print(my_type_string)
印刷品:
Pulp: type
要么:
import re
for f in file_list:
txtfile = open(f, 'r')
output[f] = []
for line in txtfile:
m = re.match('.+batch:.+(Pulp.+$)', a)
# if you just want the Type value, use the string
# '.+batch:.+Pulp:(.+$)'
if m:
pulp_value = m[1]
output[f].append(pulp_value)
for i,line in enumerate(txtfile):
if i == 4:
output[f].append(line)
elif i == 5:
output[f].append(line)
您可以使用str.find()
检查该行str.find()
字符串的索引位置。
假设“ Pulp:value”是该行的最后一段,这将导致:
start_pulp = line.find("Pulp:") # find the location
pulp_value = line[start_pulp:] # slice the string to get everything from the word "Pulp:" to the end of the line.
如果“ Pulp:value”没有一直到行尾,则可以在以下空白处拆分后续字符串。
例:
for line in txtfile:
if "Pulp:" in line:
start_pulp = line.find("Pulp:") # find the location
pulp_value = line[start_pulp:]
output[f].append(pulp_value)
或者您可以使用正则表达式-如果您沿着那条路走,Todd W的答案是完全可以接受的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.