2016-04-12 64 views
-1

Metin dosyasındaki bir sözcüğün nasıl değiştirileceğini bilen var mı?Metin dosyasındaki bir kelimenin değiştirilmesi

İşte benim stok dosyasından bir satır var:

Ben tarafından oluşturulan yeni bir numara ile 'ProductLine' yazdırırken (bu örnekte '300' olarak) benim 4 sözcüğün yerine isterler
bread 0.99 12135479 300 200 400 

Bu kodun nstock kısmı:

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 

yeni stok seviyesi (nstock)

+1

Yani neler yaşadıklarını sorun veya hata? Bunu öğrenmek için kodu çalıştırmamızı istemek yerine, bunu belirtmelisiniz. –

+1

Sadece yeni öğeler için 'itemsplit' sonra' '' .join (itemsplit) 'öğesinde doğru öğeye atayın. – cdarke

+0

Sorunu – EmDuff

cevap

0

Aslında kullanabilirsiniz regu ile 4 kelime (mevcut stok seviyesi olan) yerine geçmez Kodum Bu amaçla lar ifadeler.

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

Sen feryat çıkışı olacaktır: 'ekmek 0.99 12135479 youyou 200 400' Bu Aradığın neydi

Umut;)

+0

Teşekkür ederiz Bu, benimle "sende" (takas) ile yer değiştirecek misin? – EmDuff

+0

Tabii ki, ama alıntılar arasına koymalısın, bu yüzden bir ip olarak kabul edilir – Yoopiyoop