Python 3.2 Replace all words in a text document that are a certain length?

2024/11/16 17:59:01

I need to replace all words in a text document that are of length 4 with a different word.

For example, if a text document contained the phrase "I like to eat very hot soup" the words "like", "very", and "soup" would be replaced with "something"

Then, instead of overwriting the original text document, it needs to create a new one with the changed phrase.

Here is what I have so far:

def replacement():  o = open("file.txt","a") #file.txt will be the file containing the changed phrasefor line in open("y.txt"):  #y.txt is the original fileline = line.replace("????","something")  #see belowo.write(line + "\n")o.close()

I've tried changing "????" to something like

(str(len(line) == 4)

but that didn't work

Answer

First lets make a function that returns something if it's given a word of length 4 and the word it was given otherwise:

def maybe_replace(word, length=4):if len(word) == length:return 'something'else:return word

Now lets walk through your for loop. In each iteration you have a line of your original file. Lets split that into words. Python gives us the split function that we can use:

   split_line = line.split()

The default is to split on whitespace, which is exactly what we want. There's more documentation if you want it.

Now we want to get the list of calling our maybe_replace function on every word:

  new_split_line = [maybe_replace(word) for word in split_line]

Now we can join these back up together using the join method:

  new_line = ' '.join(new_split_line)

And write it back to our file:

  o.write(new_line + '\n')

So our final function will be:

def replacement():  o = open("file.txt","a") #file.txt will be the file containing the changed phrasefor line in open("y.txt"):  #y.txt is the original filesplit_line = line.split()new_split_line = [maybe_replace(word) for word in split_line]new_line = ' '.join(new_split_line)o.write(new_line + '\n')o.close()
https://en.xdnf.cn/q/119168.html

Related Q&A

Python split list at zeros [duplicate]

This question already has answers here:Closed 11 years ago.Possible Duplicate:Remove leading and trailing zeros from multidimensional list in Python if I have a list such as:my_list = [[1,2,0,1], [1,0…

Creating Dynamic Text Using the blit method [duplicate]

This question already has answers here:How to display text with font and color using pygame?(7 answers)Closed last year.Im creating a basic game where a black square moves around the screen. There are…

Regex to match special list items

I have weird list of items and lists like this with | as a delimiters and [[ ]] as a parenthesis. It looks like this:| item1 | item2 | item3 | Ulist1[[ | item4 | item5 | Ulist2[[ | item6 | item7 ]] | i…

How to choose the best model dynamically using python

Here is my code im building 6 models and i am getting accuracy in that, how do i choose that dynamically which accuracy is greater and i want to execute only that model which as highest accuracy."…

How do you access specific elements from the nested lists

I am trying to access elements from the nested lists. For example, file = [[“Name”,”Age”,”Medal”,”Location”],[“Jack”,”31”,”Gold”,”China”],[“Jim”,”29”,”Silver”,”US”]]This data c…

Why does BLOCKCHAIN.COM API only return recipient BASE58 addresses and omits BECH32s?

Following this post, I am trying to access all transactions within the #630873 block in the bitcoin blockchain.import requestsr = requests.get(https://blockchain.info/block-height/630873?format=json) …

rename columns according to list

I have 3 lists of data frames and I want to add a suffix to each column according to whether it belongs to a certain list of data frames. its all in order, so the first item in the suffix list should b…

How to send a pdf file from Flask to ReactJS

How can I send a file from Flask to ReactJS? I have already code that in the frontend, the user upload a file and then that file goes to the Flask server, then in the flask server the file is modify, …

How to draw cover on each tile in memory in pygame

I am a beginner in pygame and I am not a English native speaker.My assignment is coding a game called Memory. This game contains 8 pairs pictures and an cover exists on each pictures. This week, our as…

Compare 2 Excel files and output an Excel file with differences

Assume for simplicity that the data files look like this, sorted on ID:ID | Data1 | Data2 | Data3 | Data4 199 | Tim | 55 | work | $55 345 | Joe | 45 | work | $34 356 | Sam |…