简体   繁体   中英

How to replace words in python

This is my first post here. Pardon for any ignorance. Similar question have been asked on this website but this is not a duplicate.

I have this tex file. As some of you might know that wordpress.com support latex but for that one has to write the post in following manner:

$latex your-latex-code-here$

I use overleaf to write code. Now I have a tex file in hand but replacing every $ by $latex is very tedious. So I was thinking of using python to do the dirty work for me.

I know how replace function works. How to search and replace text in a file using Python?

import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')

or

# Read in the file
with open('file.txt', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('ram', 'abcd')

# Write the file out again
with open('file.txt', 'w') as file:
  file.write(filedata)

But the problem is that it will replace both the $ signs. For example if I have some thing like this:

Let $x$ be a real number. Then we define square of $x$ as $x^2$.

If I run this code it will return the output as :

Let $latex x$latex be a real number. Then we define square of $latex x$latex as $latex x^2$latex.

which is meaningless. I just want first dollar sign to be replaced. I tried to think but I am stuck.

Try using this regular expression in your code:

import re

s = 'Let $x$ be a real number. Then we define square of $x$ as $x^2$.'
re.sub(r'\$(.+?)\$', r'$latex \1$', s)

There's no need to split/join the original string (that will mess the Latex text!), and the result will look like this:

'Let $latex x$ be a real number. Then we define square of $latex x$ as $latex x^2$.'

You can do this by splitting the original string and replacing only the first instance of $ in each word.

s = "Let $x$ be a real number. Then we define square of $x$ as $x^2$."
r = [i.replace("$", "$latex ", 1) for i in s.split()]
print(" ".join(r))
# Let $latex x$ be a real number. Then we define square of $latex x$ as $latex x^2$.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM