如果在python中满足条件,则替换字符串

时间:2019-04-04 16:03:33

标签: python

我有一个看起来像这样的文件,如果文件中的摘要=“ 3ghi”(我可能是“ 3ghi”或5“ ghi”),则条件大于4应更改为“ new”,条件< = 2应该更改为“ fair”。我在下面添加了我的代码,replace命令有效,但是我的if循环不好。请帮忙。

Input:
<code=report docket="3ghi" parse=20>
    <items="20" product="abc" condition="9">
    <items="50" product="xyz" condition="8">
    <items="" product="mno" condition="2">

Output:
<code=report docket="3ghi" parse=20>
    <items="20" product="abc" condition="new">
    <items="50" product="xyz" condition="new">
    <items="" product="mno" condition="fair">

with open(("test.txt",'r') as new:
   readin = new.read
   if "docket =3ghi" == True:
        readin.replace('condition="4-100"', 'condition="new"')
        readin.replace('condition="1-2"', 'condition="fair"')
        x.write(readin)

4 个答案:

答案 0 :(得分:2)

第一个问题:

readin = new.read

您没有调用该方法,也不会在readin中获得文件内容

第二个问题:

if "docket =3ghi" == True:

您正在比较字符串是否为True-永远不会为True

答案 1 :(得分:2)

让我们细分您当前的声明:

if "docket = 3ghi" == True:

非空字符串的计算方式类似于True,但并非完全相同。 TrueTrue是布尔值,因此您要问“此字符串是否是布尔值?”那总是False

"somestr" == True
# False

修复该问题,以检查字符串是否是文件的一部分in。例如:

with open(("test.txt",'r') as new:
    for line in new.read(): # read in the file and iterate
         if "somestr" in line:
             # do something

请注意,我也已将括号添加到new.read()中,以免出现function doesn't support iteration这样的异常情况

答案 2 :(得分:0)

您的第一个问题是使用read及其方法读取文件。

new.read()

其次,您正在检查

"docket=3ghi" 

存在于文件中,多数民众赞成在没有完成。您应该先进行迭代,例如

for i in reading:
    if "your string" in i:
        print("Put your action here")

就这样。

答案 3 :(得分:0)

您需要正确地调用该方法,以将文件的全部内容包含在null中。现在,您可以readin两次也可以正确检查情况了

replace