replace text in a txt - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: replace text in a txt (/thread-40909.html) Pages:
1
2
|
replace text in a txt - cartonics - Oct-12-2023 # Read in the file with open('lista.txt', 'r') as file: filedata = file.read() # Replace the target string filedata = filedata.replace('Verona', 'Hellas Verona') # Write the file out again with open('fileok.txt', 'w') as file: file.write(filedata)i have a txt with some text in this structure is it possible to replace all text inside it? and not for only one?Verona -> Hellas Verona Sassuolo -> Sassuolo Calcio Monza -> Ac Monza and remove all 11.11% and -1.11% RE: replace text in a txt - buran - Oct-12-2023 (Oct-12-2023, 07:50 AM)cartonics Wrote: is it possible to replace text inside it?Yes, it's possible. What have you tried so far and what specific problem do you have? RE: replace text in a txt - cartonics - Oct-12-2023 i have to add all this lines? filedata = filedata.replace('Verona', 'Hellas Verona') filedata = filedata.replace('Sassuolo', 'Sassuolo Calcio')one fo each? or there is a faster way? RE: replace text in a txt - buran - Oct-12-2023 you can use a dict that maps old:new values and loop over it, instead or writing multiple repetitive lines replacements = {'Verona':'Hellas Verona', 'Sassuolo':'Sassuolo Calcio'} for old_val, new_val in replacements.items(): fielddata = filedata.replace(old_val, new_val) RE: replace text in a txt - perfringo - Oct-12-2023 One way is to define required replacements in dictionary, then iterate over rows in file, split row to words and replace if needed or keep and write to new file. I haven't tested it but something like this should work (this takes advantage of dict.get method where it is possible to provide default value when key is not found): replacements = {"Verona": "Hellas Verona", "Sassuolu": "Sassuolu Calcio", "Monza": "AC Monza", "11.11%": "", "-1.11%": ""} with open("source.txt", "r") as source, open("output.txt", "w") as target: for line in source: print(" ".join(replacements.get(word, word) for word in line.split()), file=target) RE: replace text in a txt - cartonics - Oct-12-2023 Thank you so much for the methods and i come with a new question: i want to build an insert query for each match from that file and then send it to my own database.. for example from Verona - Napoli 10.42% (9.60) 1.11% 1 27.08% (3.69) 11.11% X 62.5% (1.60) -11.11% 2 37.5% (2.67) 11.11% 1X 89.58% (1.12) -1.11% X2 72.92% (1.37) -11.11% 12 create the query INSERT INTO sbostats (partita,p1,pX,p2,p1x,px2,p12) VALUES ("Verona - Napoli","10.42% (9.60) 1.11% 1" ,"27.08% (3.69) 11.11% X ","62.5% (1.60) -11.11% 2 ","37.5% (2.67) 11.11% 1X " ," 89.58% (1.12) -1.11% X2"," 72.92% (1.37) -11.11% 12 " ); and so on... i have to take the number of rows of file and then do same from line 1 to 7 than 8 to 14 and so on? import mysql.connector from mysql.connector import errorcode mydb = mysql.connector.connect( host="localhost", user="root", database="my_db" ) mycursor = mydb.cursor() sql = "INSERT INTO sbostats (partita,p1,pX,p2,p1x,px2,p12) VALUES (%s, %s,%s, %s,%s, %s, %s)" val = ("test1", "test2","3", "4", "5", "6", "7") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.")i saw also that i can connect to my database :) and i can send the query .. All was fine so i have to put datas in "val" and iterate.. but i have no idea how to do that! RE: replace text in a txt - deanhystad - Oct-12-2023 It is easy to read the group the lines. You can even do the string replacement at the same time. from itertools import batched names = { "Verona": "Hellas Verona", "Sassuolu": "Sassuolu Calcio", "Monza": "AC Monza", } with open("test.txt", "r") as file: for values in batched(file, 7): values = [value.strip() for value in values] a, b = values[0].split(" - ") values[0] = f"{names.get(a, a)} - {names.get(b, b)}" print(values)If you aren't using Python 3.12 or newer, you can make your own batched. from itertools import islice names = { "Verona": "Hellas Verona", "Sassuolu": "Sassuolu Calcio", "Monza": "AC Monza", } def batched(iterable, n): "Batch data into tuples of length n. The last batch may be shorter." # batched('ABCDEFG', 3) --> ABC DEF G if n < 1: raise ValueError("n must be at least one") it = iter(iterable) while batch := tuple(islice(it, n)): yield batch with open("test.txt", "r") as file: for values in batched(file, 7): values = [value.strip() for value in values] a, b = values[0].split(" - ") values[0] = f"{names.get(a, a)} - {names.get(b, b)}" print(values)I don't see any value in putting this information in a database. A database needs to be carefully designed to be useful. If you could put this information into a database, what kind of queries would you want to perform? Use the queries to define what tables and columns you'll need in your database, then write the code to load the file into database tables. Don't create the tables first then try to figure out how to write a query. RE: replace text in a txt - cartonics - Oct-13-2023 Quote:I don't see any value in putting this information in a database. A database needs to be carefully designed to be useful. If you could put this information into a database, what kind of queries would you want to perform? Use the queries to define what tables and columns you'll need in your database, then write the code to load the file into database tables. Don't create the tables first then try to figure out how to write a query. from this txt file i need only the percentages Verona - Napoli partita column 10.42% p1 column 27.08% px column 62.5% p2 column 37.5% p1X column 89.58% pX2 column 72.92% p12 column so i need to create and send inserts like sql = "INSERT INTO sbostats (partita,p1,pX,p2,p1x,px2,p12) VALUES (%s, %s,%s, %s,%s, %s, %s)" val = ( "Verona - Napoli", "10.42%", "27.08%","62.5%", "37.5%", "89.58%", "72.92%") one for each 7 lines (match) of the txt file then i will make some joins/query and view on other tables of my database. RE: replace text in a txt - deanhystad - Oct-13-2023 I still see no value here. How can you look up those percentages in the database? Try writing the query that would retrieve them. RE: replace text in a txt - cartonics - Oct-13-2023 (Oct-13-2023, 11:35 AM)deanhystad Wrote: I still see no value here. How can you look up those percentages in the database? Try writing the query that would retrieve them. will be something like this: "SELECT * from calcio inner join sbostats on sbostats.partita = calcio.partita"; but for now i have to insert data from txt to the database so something like: INSERT INTO sbostats (partita,p1,pX,p2,p1x,px2,p12) VALUES ( "Verona - Napoli", "10.42%", "27.08%","62.5%", "37.5%", "89.58%", "72.92%") i can also add that columns in the table calcio via insert update with where clause.. but my problem is to build the insert query from txt to database |