[英]Parsing the String to different format in Python
我有一个文本文档,我需要在数组中的关键字之前添加两个 @ 符号。
示例文本和数组:
str ="This is a sample text document which consists of all demographic information of employee here is the value you may need,name: George employee_id:14296blood_group:b positive this is the blood group of the employeeage:32"
arr=['name','employee_id','blood_group','age']
所需文字:
str ="This is a sample text document which consists of all demographic information of employee here is the value you may need, @@name: George @@employee_id:14296 @@blood_group:b positive this is the blood group of the employee @@age:32"
只需使用replace
function
str ="This is a sample text document which consists of all demographic information of employee here is the value you may need,name: George employee_id:14296blood_group:b positive this is the blood group of the employeeage:32"
arr = ['name','employee_id','blood_group','age']
for w in arr:
str = str.replace(w, f'@@{w}')
print(str)
您可以简单地循环 arr 并使用 str.replace function:
for repl in arr:
strng.replace(repl, '@@'+repl)
print(strng)
但是,我强烈建议您更改变量名str
,因为它是保留关键字。
您可以替换该值并在替换值之前添加空格和双倍@@,并在结果中将双倍空格替换为一个空格。
str ="This is a sample text document which consists of all demographic information of employee here is the value you may need,name: George employee_id:14296blood_group:b positive this is the blood group of the employeeage:32"
arr=['name','employee_id','blood_group','age']
for i in arr:
str = str.replace(i, " @@{}".format(i))
print(str.replace(" ", " "))
Output
This is a sample text document which consists of all demographic information of employee here is the value you may need, @@name: George @@employee_id:14296 @@blood_group:b positive this is the blood group of the employee @@age:32
您可以按照以下方式将re
模块用于该任务
import re
txt = "This is a sample text document which consists of all demographic information of employee here is the value you may need,name: George employee_id:14296blood_group:b positive this is the blood group of the employeeage:32"
arr=['name','employee_id','blood_group','age']
newtxt = re.sub('('+'|'.join(arr)+')',r'@@\1',txt)
print(newtxt)
Output:
This is a sample text document which consists of all demographic information of employee here is the value you may need,@@name: George @@employee_id:14296@@blood_group:b positive this is the blood group of the employee@@age:32
说明:这里我使用正则表达式从您的列表中捕获单词并将每个单词替换为@@word。 这是单遍,而不是使用多个 str.replace 时的 X 遍(其中 X 是arr
的长度),因此对于arr
很长的情况应该更有效。
作为替代方案,您可以在循环中将以下内容转换为更长的列表。 @@ 之前似乎也有空格。
str= str[:str.find(arr[0])] + ' @@' + str[str.find(arr[0]):]
str= str[:str.find(arr[1])] + ' @@' + str[str.find(arr[1]):]
str= str[:str.find(arr[2])] + ' @@' + str[str.find(arr[2]):]
str= str[:str.find(arr[3])] + ' @@' + str[str.find(arr[3]):]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.