更改txt fi中特定字符串后面的值

2024-04-19 11:47:38 发布

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

这听起来像是一个常见的问题要解决,但我从来没有找到一个适当的解决办法。 我有一个txt文件,看起来像:

variable_name1 = '1'
variable_name2 = '0'

等等

因此,我想编写一个Python脚本,在txt文件中找到一行,该行与variable_name1(函数的输入)相反,并将变量设置为x(也是一个输入)。 到目前为止,我已经尝试了:

line = "Cats = '2'"
matchObj = re.match( r'Cats = (.*)', line)
print("matchObj.group(1) : ", matchObj.group(1))
k=(matchObj.group(1))
print(k)

不过,我希望猫能成为一种输入。我想从一个包含多行的txt文件中找到它。你知道吗


Tags: 文件函数retxt脚本matchlinegroup
2条回答

您只需将变量名赋给一个变量,然后将其包含在正则表达式中,如以下示例所示:

line = "Cats = '2'"
variable_name = "Cats"

import re
f = re.findall(word+" = '(.*)'", line)
print f

输出:

['2']

希望这有帮助。你知道吗

您可以使用列表格式完成此操作:

简单示例:

>>> word = 'This'
>>> print('{} is string formatting'.format(word))
This is string formatting

您的代码具体如下:

line = "Cats = '2'"
word = str(input('Enter keyword: '))

matched = re.match('{} = (.*)'.format(word), line).group(0)
print(matched)

>>> python script.py
Enter keyword: Cats
Cats = '2'

>>> word = 'Dogs'
>>> print(re.match('{} = (.*)'.format(word), "Dogs = '3'").group(0))
Dogs = '3'

相关问题 更多 >