替换文本文件中的单词

时间:2016-04-12 14:50:31

标签: python text-files

有谁知道如何替换文本文件中的单词?

这是我的股票档案中的一行:

bread 0.99 12135479 300 200 400 

当我使用此代码的nstock部分创建的新数字打印'productline'时,我希望能够替换我的第四个单词(在本例中为'300'):

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

我的代码不会用新的库存水平(nstock)替换第四个单词(这是当前的库存水平)

1 个答案:

答案 0 :(得分:0)

实际上,您可以为此目的使用正则表达式。

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 youyou 200 400'

希望这就是你要找的东西;)