Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

[python] Najit a nahradit python (dělení)

12 views
Skip to first unread message

Jiří Kameník

unread,
Nov 4, 2021, 5:38:10 PM11/4/21
to
Ahoj, mám tady takovém Python script, který jsem zkopíroval z netu a funguje mi dobře.
Dělá přesně to co jsem po něm chtěl, najde a nahradí například tohle:(re.compile(r'dog'), 'cat'), ale já bych teď potřeboval aby mi například z "<CISLO>1000</CISLO>" udělal dělení tisícovkou a nahradil to za "<CISLO>1.000</CISLO>"
Šlo by to nějak zakomponovat do tohoto scriptu? Vůbec si s tím nevím rady.
Zkoušel jsem tohle:
(re.compile(r'<CISLO>(\d\d\d\d)</CISLO>'), '<CISLO>\\1</CISLO>'),
to prošlo, ale bezezměny, pochopitelně. Pak jsem zkoušel různě:
(re.compile(r'<CISLO>(\d\d\d\d)</CISLO>'), '<CISLO>\\1 // 1000</CISLO>'),
a různé další variace, ale nic mi neprošlo :(
Mohl bych požádat o pomoc zkušenější?
Moc Děkuji Ston3

KÓD:
import os, os.path, re

path
= "/Users/mypath/testData"
myfiles
= os.listdir(path)
# its much faster if you compile your regexes before you
# actually use them in a loop
REGEXES
= [(re.compile(r'dog'), 'cat'),
         
(re.compile(r'123'), '789')]
for f in myfiles:
   
# split the filename and file extension for use in
   
# renaming the output file
    file_name
, file_extension = os.path.splitext(f)
    generated_output_file
= file_name + "_regex" + file_extension

   
# As l4mpi said ... if odt is zipped, you'd need to unzip it first
   
# re.search is slower than a simple if statement
   
if file_extension in ('.txt', '.doc', '.odt', '.htm', '.html'):

       
# Declare input and output files, open them,
       
# and start working on each line.
        input_file
= os.path.join(path, f)
        output_file
= os.path.join(path, generated_output_file)

       
with open(input_file, "r") as fi, open(output_file, "w") as fo:
           
for line in fi:
               
for search, replace in REGEXES:
                    line
= search.sub(replace, line)
                fo
.write(line)
       
# both the input and output files are closed automatically
       
# after the with statement closes
0 new messages