Replacing a word in a file

Replacing a word in a file

By : user2185491
Date : November 22 2020, 04:01 AM
With these it helps Python has string.replace(old, new)-method. You are trying now to replace one word with a list and this will result in an error. Here is an example how you should go through whole text:
code :
from random import randint

with open("text_msg_file.txt", 'rb') as f:
    lines = f.readlines()

# Text file containing bad words, assume only one word/line
with open("badcontent.txt", 'rb') as f:
    badcontent = f.readlines()

# Text file containing good words, assume only one word/line
with open("goodcontent.txt", 'rb') as f:
    goodcontent = f.readlines()

# Strip new line character from words
lines = [word.strip("\n") for word in lines]
badcontent = [word.strip("\n") for word in badcontent]
goodcontent = [word.strip("\n") for word in goodcontent]

for i in range(len(lines)):
    line = lines[i]
    # List of words on single line. Line splitted from whitespaces
    words = line.split(" ")
    # Loop through all words
    for j in range(len(words)):
        # Get random integer for index
        index = randint(0, len(goodcontent))
        if words[j] in badcontent:
            # Replace bad word with a good word
            words[j] = goodcontent[index]
    # Join all words from a list into a string
    line = " ".join(words)
    # Put string back to list of lines
    lines[i] = line
# Join all lines back into one single text
new_text = "\n".join(lines)
with open("new_msg.txt", "wb") as f:

Share : facebook icon twitter icon
Replacing a word in any given file using VBS

Replacing a word in any given file using VBS

By : Sotiris Damouras
Date : March 29 2020, 07:55 AM
help you fix your problem I am not hands on in VB Script. , Something like this should work:
code :
Set fso = CreateObject("Scripting.FileSystemObject")

filename = "C:\Windows\your.ini"

text = Split(fso.OpenTextFile(filename).ReadAll, vbNewLine)
text(1) = CreateObject("WScript.Network").ComputerName
fso.OpenTextFile(filename, 2).Write Join(text, vbNewLine)
i want to change the text in a file, my code is searching the word but not replacing the word

i want to change the text in a file, my code is searching the word but not replacing the word

By : user3234050
Date : March 29 2020, 07:55 AM
I wish this helpful for you First, make sure you are assigning the result of the replace to something, otherwise it's lost, remember, String is immutable, it can't be changed...
code :
line = line.replace("1.1.0","1.1.1");
File original = new File("G:/backup/default0/default.js");
File tmp = new File("G:/backup/default0/tmpdefault.js");
boolean replace = false;
try (FileReader fr = new FileReader(original);
                BufferedReader br = new BufferedReader(fr);
                FileWriter fw = new FileWriter(tmp);
                BufferedWriter bw = new BufferedWriter(fw)) {
    String line = null;
    while ((line = br.readLine()) != null) {
        if (line.contains("1.1.0")) {
            line = line.replace("1.1.0", "1.1.1");
            System.out.println("String replaced");
    replace = true;
} catch (Exception e) {
// Doing this here because I want the files to be closed!
if (replace) {
    if (original.delete()) {
        if (tmp.renameTo(original)) {
            System.out.println("File was updated successfully");
        } else {
            System.err.println("Failed to rename " + tmp + " to " + original);
    } else {
        System.err.println("Failed to delete " + original);
Replacing a word in a config file is inserting the new word in other configs that are partly the same.

Replacing a word in a config file is inserting the new word in other configs that are partly the same.

By : Avinash Krishna
Date : March 29 2020, 07:55 AM
Hope this helps So I have a script that I was building to replace words in a very large config file that I am rebuilding and renaming. So I will give an example of what it is that is going on. Lets say in the server line of the load balancer config I have "web01" and want to change it to "web01_svr", it works fine. But on the "add service" line I might have "web01-80-HTTP_sg". The script is inserting itself to make it "web01_svr-80-HTTP_sg". How do I specify in this script to only match exact objects and not partial? , Regex to the rescue:
code :
import re

filedata = re.sub(r'\b'+ old +r'\b(?![-])', new, filedata)
Replacing a word depending upon the previous and next word in a file using java

Replacing a word depending upon the previous and next word in a file using java

By : mpcaddy
Date : March 29 2020, 07:55 AM
I hope this helps . You can use Pattern with this regex (.*?\s+.*?\s+)(.*?)(\s.*) or ((.*?\\s+){2})(.*?)(\\s.*) like this
code :
String query = "INSERT INTO table_name VALUES";

Pattern pattern = Pattern.compile("(.*?\\s+.*?\\s+)(.*?)(\\s.*)");
Matcher matcher = pattern.matcher(query);
while (matcher.find()) {
    query = matcher.group(1) + 
            String.format("[%s]", matcher.group(2).toUpperCase()) + 

Replacing a certain word in a txt file

Replacing a certain word in a txt file

By : Theresa M Bosco
Date : March 29 2020, 07:55 AM
it fixes the issue Be careful you have to change only the line concerned, many users could have the same passeword, so you have to read the file by line , identify the login concerned and of course not replace anything because also the login or avatar could has the same value as the password, but recreate the line with the new info, and after save the file with the new whole text value.
And just an advice for such needs it's better to use relational database.
Related Posts Related Posts :
  • Decompose string of different symbols in python
  • pandas merge and group concat
  • How to traverse tree for making binary code from a HuffmanTree?
  • Check if IP is in network on Python3
  • non equally spaced points along x-axis in a plot
  • Concatenation of text files consisting list of lists?
  • Use regex to parse characters on a line of text
  • pandas df.fillna - filling NaNs after outer join with correct values
  • How can I undo a time series conversion of a pandas dataframe?
  • Virtual environment is not working in Django
  • FileNotFoundError in Python during Arabic text analysis
  • How to read email using python and smtplib
  • How to write a function which takes a string and turns into a single digit?
  • Linear Regression without Least Squares in sklearn
  • Matplotlib - Box plot with number of occurrence of data?
  • Finding the numbers in a given range who have a perfect square for the sum of their divisors and returning them with the
  • How do I put y(a) and y(b) initial conditions in odeint(python) instead of y(0) and y'(0)?
  • Import Error in Tensorflow in Jupyter Notebook
  • How to convert a mapping of ranges into a dictionary
  • lxml scraping overwrite error due to missing element
  • How can I run different codes from different editor tabs on the Spyder on the same console (as opposed to different tabs
  • urllib3 connectionpool - Connection pool is full, discarding connection
  • How to change django-filter filtering key?
  • Python Google Sheets API Limit 429 Error with Loop
  • How can I turn this DataFrame into a DataFrame with average score by Index Value?
  • summing element in a range for all element in an array
  • pm2 json file format for python script
  • Mask dataframe column based on datetime index
  • Brute force stable marriage, How to implements all possible pairs between 2 lists?
  • Rounding hours of datetime in PySpark
  • Show data only from one cluster
  • ValueError: Cannot feed value of shape (64,) for Tensor 'x:0', which has shape '(?, 128, 128, 1)'
  • Python try except not working with np.arccos
  • Grouping by and Combining the Strings
  • python threading.local() in different module
  • Or keyword for pandas series
  • Python Django using wsgi.py with apache2 loads filter fields out of order every restart
  • Using FireStore in Google Dataflow
  • Filter a DataFrame By Date One Week Previous From Current Date
  • How to transpose pandas dataframe to cross-tabulate dataframe keeping all values
  • How best way to transform one list into new list with pairs of elements from list?
  • Conditionals in numpy. How can i put 3 or more into my dataframe using pandas or numpy?
  • Failed to specific gcc version when setup python
  • LSTM hyperparameters not available in model.summary() after loading model
  • creating pandas-vectorized 'subtraction' table
  • Python configuration in Windows - Module locations - pip vs Eclipse/Liclipse
  • CUDA_ERROR_INVALID DEVICE with keras=2.0.5 and tensorflow-gpu=1.2.1
  • Is it safe to use next within a for loop in Python?
  • PORTING usage of s3curl.pl to Python
  • How to install Python 3.5.5?
  • Python 3.7 - PIP upgrade error on windows 10
  • How can I fix this function?
  • Optimizing execution time for appending data (Python)
  • Why my Depth function returns the Height of Binary tree not the depth?
  • How to access values of a class from a different method(out the class)
  • Groupby to create new columns
  • Fabric - ThreadingGroup exception stops remaining requests?
  • Timezone conversion with pyspark from timestamp and country
  • I want to create a table and select the value using row and column using python
  • Extract data from a span with BeautifulSoup
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org