我想用regex替换文件中的多个模式。到目前为止,这是我的(工作)代码:
import re
with open('test.txt', "r") as fp:
text = fp.read()
result = re.sub(r'pattern', 'replacement', str)
result2 = re.sub(r'anotherpattern', 'anotherreplacement2', result)
...
with open('results.txt'
我想用随机数字替换文本文件中的所有电子邮件地址。现在我已经找到了这些电子邮件,但是它们都是由正则表达式re.findall()在列表中返回的。
例如,输出如下:
['xyz123@gmail.com']
因此,当我尝试用随机数替换这个输出时,我会得到错误信息
Can't convert 'list' object to str implicitly
我的代码如下:
with open('a.txt', 'r') as file1:
with open('b.txt', 'w') as
我正在试着做一个删除字符串中所有元音的程序,但是由于某些原因它不起作用。以下是我在python 3中的代码
s = list(input())
vowels = ["A", "E", "I", "O", "U", "Y", "a", "e", "i", "o", "u", "y"]
for i in s:
if i in vowels:
s.remove(i)
除了当两个元音彼
我有一个包含这类字符串"1405079/1“的文件,其中唯一常见的是末尾的"/1”。我希望能够找到这些字符串并删除它们,下面是示例代码,但它没有做任何事情。
with open("jobstat.txt","r") as jobstat:
with open("runjob_output.txt", "w") as runjob_output:
for line in jobstat:
string_to_replace = ' */1'
“熊猫DataFrame”包含一个列,列中有以花括号表示的描述和占位符:
descr replacement
This: {should be replaced} with this
任务是用同一行中另一列的文本替换大括号中的文本。不幸的是,这并不像:
df["descr"] = df["descr"].str.replace(r"{*?}", df["replacement"])
~/anaconda3/lib/python3.6/site-packages/pandas/co
我有一个这样的字符串:
Hi. My name is _John_. I am _20_ years old.
我想把它转换成这样:
Hi. My name is <b>John</b>. I am <b>20</b> years old.
我做了这样的事情,但没有运气。
import re
text = "Hi. My name is _John_. I am _20_ years old."
pattern = "(.*)(\_)(.*)(\_)(.*)"
re.sub(pattern, r'\1<
我试图从python中的字符串中删除除数字(数字0-9)以外的所有字符和特殊符号。我就是这么做的-
s='das dad 67 8 - 11 2928 313'
s1=''
for i in range(0,len(s)):
if not(ord(s[i])>=48 and ord(s[i])<=57):
s1=s1+' '
else:
s1=s1+s[i]
#s1=s1.split()
print(s1)
所以,基本上我检查每个字符的ascii代码,如果它们不位
我有一个文本文件,它由以下一般格式的行组成:
5.1: 23
10.145: 34
等。
我需要Python代码,它输出每一行的内容,以便删除句点.之后和冒号:之前的字符。
也就是说,它将输出上述内容
5: 23
10: 34
到目前为止,我有以下代码,用于类似于文本文件的编辑:
with open("file.txt", "r") as f:
with open("newfile.txt", "w") as output:
for line in f:
output.write
我正在尝试替换文件中的字符串,即版本号4.0.0到5.0.0。但是,在使用replace方法时,24.0.0之类的版本也会发生更改,这是不可取的。
例如:我希望在整个文件中将4.0.0更改为5.0.0。但是,24.0.0应该保持原样。
我写了简单字符串替换的代码,这里是我的文件
fo = open ('ex.txt', 'r')
for line in fo:
print(line.replace('4.0.0', '5.0.0'))
示例输入:
This is a file
It contains a version n
我需要使用数组替换字符串中的某些内容,它们可以如下所示:
array = [3, "$x" , "$y", "$hi_buddy"]
#the first number is number of things in array
string = "$xena is here $x and $y."
我有另一个数组来替换这些东西,比方说它叫做rep_array。
rep_array = [3, "A", "B", "C"]
对于替换者,我使用以下方法:
for x in range (