Python子进程中的特殊字符问题

2024-09-30 14:37:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我翻译了这句话:

awk '/\]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1' filename2 > filename1  

在这个Python代码中

^{pr2}$

但是,输出文件是空的,在我使用bash时不是空的。在

有了这个:

call(['awk', r"'/\]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1'"], stdout=f)

我明白了

awk: '/]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1' awk: ^ invalid char ''' in expression

示例输入文件:

Interval: [ some_value some_value1]:
Interval: [ some_value some_value2]:
some text here1 
some text here2
some text here3
some text here4
Interval: [ some_value some_value3]:
Interval: [ some_value some_value4]:
Interval: [ some_value some_value5]:
Interval: [ some_value some_value6]:
some text here5
some text here6
some text here7
some text here8
Interval: [ some_value some_value7]:
Interval: [ some_value some_value8]:

示例输出文件:

Interval: [ some_value some_value2]:
some text here1
some text here2
some text here3
some text here4
Interval: [ some_value some_value6]:
some text here5
some text here6
some text here7
some text here8

Tags: 文件text示例valuesomenrnextprint
1条回答
网友
1楼 · 发布于 2024-09-30 14:37:16

我打赌你的字符串转换有问题。Python版本提供:

>>> print('/\\\]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1')
/\\]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1

而shell版本给出了。在

^{pr2}$

您可以使用原始字符串表示法简化此类内容:

>>> print(r'/\]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1')
/\]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1

根据文件:

When an r or R prefix is present, backslashes are still used to quote the following character, but all backslashes are left in the string. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase `n'. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote

你的命令是:

call(['awk', r'/\]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1', filename2], stdout=f)

相关问题 更多 >