替换文本文件中的单词

2024-09-24 22:31:47 发布

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

有人知道如何替换文本文件中的单词吗?你知道吗

我的股票档案里有一行:

bread 0.99 12135479 300 200 400 

当我打印“productline”时,我希望能够将我的第4个单词(在本例中为“300”)替换为由以下代码的nstock部分创建的新数字:

for line in details: #for every line in the file:
        if digits in line: #if the barcode is in the line 
            productline=line #it stores the line as 'productline'
            itemsplit=productline.split(' ') #seperates into different words
            price=float(itemsplit[1]) #the price is the second part of the line
            current=int(itemsplit[3]) #the current stock level is the third part of the line
            quantity=int(input("How much of the product do you wish to purchase?\n"))
            if quantity<current:
                total=(price)*(quantity) #this works out the price
                print("Your total spent on this product is:\n" + "£" +str(total)+"\n") #this tells the user, in total how much they have spent
                with open("updatedstock.txt","w") as f:
                    f.writelines(productline) #writes the line with the product in
                    nstock=int(current-quantity) #the new stock level is the current level minus the quantity

我的代码不会将第4个字(即当前库存水平)替换为新库存水平(nstock)


Tags: oftheinifislinecurrentlevel
1条回答
网友
1楼 · 发布于 2024-09-24 22:31:47

实际上,你可以使用正则表达式来达到这个目的。你知道吗

import re
string1='bread 0.99 12135479 300 200 400'
pattern='300'
to_replace_with="youyou"
string2=re.sub(pattern, to_replace_with, string1)

输出波形如下: '面包0.99 12135479优优200 400'

希望这就是你要找的;)

相关问题 更多 >