简体   繁体   English

如何在python中替换单词

[英]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. 我有这个tex文件。 As some of you might know that wordpress.com support latex but for that one has to write the post in following manner: 你们中有些人可能知道wordpress.com支持乳胶,但为此必须以以下方式编写帖子:

$latex your-latex-code-here$ $ latex-此处为latex-code $

I use overleaf to write code. 我用背面写代码。 Now I have a tex file in hand but replacing every $ by $latex is very tedious. 现在我手头有一个tex文件,但是用$ latex替换每个$非常繁琐。 So I was thinking of using python to do the dirty work for me. 所以我当时在考虑使用python为我完成肮脏的工作。

I know how replace function works. 我知道替换功能的工作原理。 How to search and replace text in a file using Python? 如何使用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: 无需拆分/加入原始字符串(这会弄乱Latex文本!),结果将如下所示:

'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$.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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