⑴ 如何只在python注释前加#,而不在整行前加#
sed 's/^[^#]/#&/' file.txt >output.txt
注:
s是sed中的替换命令。
第一个^表示行首位置,[^#]表示非#号,合起来就表示要匹配不以#开头的行。
后面用&来原封不动引用前面匹配到的行内容,在其前面加上#号。
⑵ python中的字符串怎么将里面\换成\\
a=a.replace("\\","\\\\") 单独替换似乎,是不行的
a=a.replace('\n','\\n') 但是整体替换,是可以的
⑶ python 用一个文件的特定行替换另一个文件的特定行
ls1=open("f1.txt").readlines()
ls2=open("f2.txt").readlines()
at=20
ls1[at]=ls2[at]
f=open("f3.txt","w")
forlinls1:
f.write(l)
f.close()
⑷ Python re.sub
【背景】
Python中的正则表达式方面的功能,很强大。
其中就包括re.sub,实现正则的替换。
功能很强大,所以导致用法稍微有点复杂。
所以当遇到稍微复杂的用法时候,就容易犯错。
所以此处,总结一下,在使用re.sub的时候,需要注意的一些事情。
解释具体的注意事项之前,先把其具体的解释贴出来:
re.sub
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \j are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern. For example:
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
... r'static PyObject*\npy_\1(void)\n{',
... 'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example:
>>> def dashrepl(matchobj):
... if matchobj.group(0) == '-': return ' '
... else: return '-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
'Baked Beans & Spam'
The pattern may be a string or an RE object.
The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so sub('x*', '-', 'abc') returns '-a-b-c-'.
In addition to character escapes and backreferences as described above, \g<name> will use the substring matched by the group named name, as defined by the (?P<name>...) syntax. \g<number> uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0'. The backreference \g<0> substitutes in the entire substring matched by the RE.
Changed in version 2.7: Added the optional flags argument.
re.sub的功能
re是regular expression的所写,表示正则表达式
sub是substitute的所写,表示替换;
re.sub是个正则表达式方面的函数,用来实现通过正则表达式,实现比普通字符串的replace更加强大的替换功能;
举个最简单的例子:
如果输入字符串是:
?
1
inputStr = "hello 111 world 111"
那么你可以通过
?
1
replacedStr = inputStr.replace("111", "222")
去换成
"hello 222 world 222"
但是,如果输入字符串是:
?
1
inputStr = "hello 123 world 456"
而你是想把123和456,都换成222
(以及其他还有更多的复杂的情况的时候),
那么就没法直接通过字符串的replace达到这一目的了。
就需要借助于re.sub,通过正则表达式,来实现这种相对复杂的字符串的替换:
?
1
replacedStr = re.sub("\d+", "222", inputStr)
当然,实际情况中,会有比这个例子更加复杂的,其他各种特殊情况,就只能通过此re.sub去实现如此复杂的替换的功能了。
所以,re.sub的含义,作用,功能就是:
对于输入的一个字符串,利用正则表达式(的强大的字符串处理功能),去实现(相对复杂的)字符串替换处理,然后返回被替换后的字符串
其中re.sub还支持各种参数,比如count指定要替换的个数等等。
下面就是来详细解释其各个参数的含义。
re.sub的各个参数的详细解释
re.sub共有五个参数。
其中三个必选参数:pattern, repl, string
两个可选参数:count, flags
第一个参数:pattern
pattern,表示正则中的模式字符串,这个没太多要解释的。
需要知道的是:
反斜杠加数字(\N),则对应着匹配的组(matched group)
比如\6,表示匹配前面pattern中的第6个group
意味着,pattern中,前面肯定是存在对应的,第6个group,然后你后面也才能去引用
比如,想要处理:
hello crifan, nihao crifan
且此处的,前后的crifan,肯定是一样的。
而想要把整个这样的字符串,换成crifanli
则就可以这样的re.sub实现替换:
?
1
2
3
inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (\w+), nihao \1", "crifanli", inputStr);
print "replacedStr=",replacedStr; #crifanli
第二个参数:repl
repl,就是replacement,被替换,的字符串的意思。
repl可以是字符串,也可以是函数。
repl是字符串
如果repl是字符串的话,其中的任何反斜杠转义字符,都会被处理的。
即:
\n:会被处理为对应的换行符;
\r:会被处理为回车符;
其他不能识别的转移字符,则只是被识别为普通的字符:
比如\j,会被处理为j这个字母本身;
反斜杠加g以及中括号内一个名字,即:\g<name>,对应着命了名的组,named group
接着上面的举例:
想要把对应的:
hello crifan, nihao crifan
中的crifan提取出来,只剩:
crifan
就可以写成:
?
1
2
3
inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (\w+), nihao \1", "\g<1>", inputStr);
print "replacedStr=",replacedStr; #crifan
对应的带命名的组(named group)的版本是:
?
1
2
3
inputStr = "hello crifan, nihao crifan";
replacedStr = re.sub(r"hello (?P<name>\w+), nihao (?P=name)", "\g<name>", inputStr);
print "replacedStr=",replacedStr; #crifan
repl是函数
举例说明:
比如输入内容是:
hello 123 world 456
想要把其中的数字部分,都加上111,变成:
hello 234 world 567
那么就可以写成:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
Version: 2013-05-02
Author: Crifan
Contact: admin (at) crifan.com
"""
import re;
def pythonReSubDemo():
"""
demo Pyton re.sub
"""
inputStr = "hello 123 world 456";
def _add111(matched):
intStr = matched.group("number"); #123
intValue = int(intStr);
addedValue = intValue + 111; #234
addedValueStr = str(addedValue);
return addedValueStr;
replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr);
print "replacedStr=",replacedStr; #hello 234 world 567
###############################################################################
if __name__=="__main__":
pythonReSubDemo();
第三个参数:string
string,即表示要被处理,要被替换的那个string字符串。
没什么特殊要说明。
第四个参数:count
举例说明:
继续之前的例子,假如对于匹配到的内容,只处理其中一部分。
比如对于:
hello 123 world 456 nihao 789
只是像要处理前面两个数字:123,456,分别给他们加111,而不处理789,
那么就可以写成:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
Version: 2013-05-02
Author: Crifan
Contact: admin (at) crifan.com
"""
import re;
def pythonReSubDemo():
"""
demo Pyton re.sub
"""
inputStr = "hello 123 world 456 nihao 789";
def _add111(matched):
intStr = matched.group("number"); #123
intValue = int(intStr);
addedValue = intValue + 111; #234
addedValueStr = str(addedValue);
return addedValueStr;
replacedStr = re.sub("(?P<number>\d+)", _add111, inputStr, 2);
print "replacedStr=",replacedStr; #hello 234 world 567 nihao 789
###############################################################################
if __name__=="__main__":
pythonReSubDemo();
第五个参数:flags
关于re.sub的注意事项
然后再来整理一些,关于re.sub的注意事项,常见的问题及解决办法:
要注意,被替换的字符串,即参数repl,是普通的字符串,不是pattern
注意到,语法是:
?
1
re.sub(pattern, repl, string, count=0, flags=0)
即,对应的第二个参数是repl。
需要你指定对应的r前缀,才是pattern:
r"xxxx"
不要误把第四个参数flag的值,传递到第三个参数count中了
否则就会出现我这里:
【已解决】Python中,(1)re.compile后再sub可以工作,但re.sub不工作,或者是(2)re.search后replace工作,但直接re.sub以及re.compile后再re.sub都不工作
遇到的问题:
当传递第三个参数,原以为是flag的值是,
结果实际上是count的值
所以导致re.sub不功能,
所以要参数指定清楚了:
?
1
replacedStr = re.sub(replacePattern, orignialStr, replacedPartStr, flags=re.I); # can omit count parameter
或:
?
1
replacedStr = re.sub(replacePattern, orignialStr, replacedPartStr, 1, re.I); # must designate count parameter
才可以正常工作。
⑸ python数据分析干什么
随着大数据时代的来临和Python编程语言的火爆,Python数据分析早已成为现在职场人的必备核心技能。
1、检查数据表
Python中使用shape函数来查看数据表的维度,也就是行数和列数。
2、数据表清洗
Python中处理空值的方法比较灵活,可以使用Dropna函数用来删除数据表中包含空值的数据,也可以使用fillna函数对空值进行填充。
3、数据预处理
数据预处理是对清洗完的数据进行整理以便后期的统计和分析工作,主要包括数据表的合并、排序、数值分列、数据分组及标记等工作。
4、数据提取
主要是使用三个函数:loc、iloc和ix,其中loc函数按标签值进行提取,iloc按位置进行提取,ix可以同时按标签和位置进行提取。
5、数据筛选汇总
Python中使用loc函数配合筛选条件来完成筛选功能,配合sum和 count函数还能实现excel中sumif和countif函数的功能。
希望可以帮到你
⑹ 急急急,python删除指定匹配字符串的行!
withopen('filename')asf:
withopen('writefile','w')aswf:
forlineinf.readlines():#遍历每一行
ifline.strip()!='patternstring':#如果不匹配则写入文件
wf.write(line)
中间的filename,writefile和pattern string都替换成你想要的,输入文件名,输出文件名,匹配字符串内容
⑺ python(pandas模块)
1.什么是pandas? numpy模块和pandas模块都是用于处理数据的模块。 numpy主要用于针对数组进行统计计算,处理数字数据比较方便。 pandas除了可以处理数字数据,还可...
⑻ python如何替换文件指定内容
你是把
str.replace(p1,
p2)
当成本地执行的了。
即针对变量本身操作的了。
我所知道的,除了有限的几个,比如list的reverse等,是直接针对变量本身操作的。
其他的,都是只是执行对应动作而已。
包括你这里的replace,所以需要把替换后的结果,返回到某个变量中,然后再打印出来,就可以看到变化了。
顺带说一句,如果针对处理html的内容的话,倒是建议你用第三方库函数。
原因见:
【整理】关于用正则表达式处理html代码方面的建议
(这里不给贴地址,所以请自己用google搜标题,即可找到帖子地址)
=======================
评论里面没法发表,写在这里给你看:
看来,你本身对于回车和换行的概念,就不是很清楚,所以建议你去看我总结的:
【详解】回车
换行
0x0d
0x0a
cr
lf
r
n的来龙去脉
如果想换成回车换行,那么就是类似于这样的写法:
replacedstr
=
str.replace("
",
"\r\n");
同理:(这里不给贴地址,所以请自己用google搜标题,即可找到帖子地址)
⑼ python怎么把字符串最后一个字符去掉
1、先将字符串转换成列表,之后再修改列表中的元素来完成,通过list(r)来将r字符串转化成了一个列表。
⑽ Python中字符串常用操作有哪些
字符串是 Python
中常用的数据类型,我们可以使用引号('或")来创建字符串,对字符串进行使用和操作,需要用到特定的函数,以下是常用的Python字符串操作方法:
1. capitalize()
作用:capitalize() 主要是用来实现字符串首字母大写,其他字母小写的功能。
实例:
1
2str1 = "oldboy"
print(str1.capitalize())
输出结果:Oldboy
2. swapcase()
作用:swapcase() 主要是用来实现字符串大小写反转。
实例:
1
2str1 = " Oldboy"
print(str1.swapcase())
输出结果:oLDBOY
3. title()
作用:title() 主要是用来实现字符串非字母隔开的部分,首字母大写,其余字母小写。
实例:
1
2str1 = "Old boy e com"
print(str1.title())
输出结果:Old Boy E Com
4. upper()
作用:upper() 主要是用来实现字符串所有字母全部大写。
实例:
1
2str1 = "Oldboye"
print(str1.upper())
输出结果:OLDBOYEDU
5. lower()
作用:lower() 主要是用来实现字符串所有字母全部小写。
实例:
1
2str1 = "oLDBOYEDU"
print(str1.lower())
输出结果:oldboye
6. center()
作用:center() 主要是用来实现字符串内容居中,填充物默认为空。
实例:
1
2
3str1 = "Oldboye"
print(str1.center(15))
print(str1.center(15,"*"))
输出结果:
Oldboye
***Oldboye***
7. find()
作用:find() 主要作用是通过元素找索引,可以整体找,可以切片,找不到则返回-1。
实例:
1
2
3str1 = "Oldboye"
print(str1.find('b'))
print(str1.find('A'))
输出结果:3 -1
8. index()
作用:index() 主要作用是通过元素找索引,可以整体找,可以切片,找不到会报错。
实例:
1
2
3str1 = " Oldboye "
print(str1.index("b"))
print(str1.index("A"))
输出结果:
0
Traceback (most recent call last):
File "", line 1, in
ValueError: substring not found
9. startswith(obj)
作用:startswith(obj) 主要作用是检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。
实例:
1
2str1 = "Oldboye"
print(str1.startswith("O"))
输出结果:True
10. endswith(obj)
作用:endswith(obj) 主要作用是检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。
实例:
1
2str1 = " Oldboye "
print(str1.endswith("e"))
输出结果:True
11. strip()
作用:strip() 主要作用是去除字符串前后两端的空格或其他字符、换行符、tab键等。
实例:
1
2
3
4str1 = "***Oldboy***"
print(str1.strip("*")) #去除两边的*
print(str1.lstrip("*")) #去除左边的*
print(str1.rstrip("*")) #去除右边的*
输出结果:
Oldboy
Oldboy***
***Oldboy
12. replace(oldstr, newstr)
作用:replace(oldstr, newstr)主要作用是替换字符串。
实例:
1
2str1 = "Oldboye"
print(str1.replace("boy","man"))
输出结果:Oldmane
13. isalpha()
作用:isalpha()主要作用是要判断字符串是否只由字母组成,是返回Ture,否返回False。
实例:
1
2
3
4str1 = "Oldboye"
str2 = “Old boy e”
print(str1.isalpha())
print(str2.isalpha())
输出结果:True False
14. isdigit()
作用:isdigit()主要作用是判断字符串是否只由数字组成,是返回Ture,否返回False。
实例:
1
2
3
4str1 = "Oldboye"
str2 = “520”
print(str1.isdigit())
print(str2.isdigit())
输出结果:False True
15. format()
作用:format()主要作用是格式化字符串。
方式一:按位置传参
1
2str1 = '我叫{},今年{}岁'.format('oldboy',30)
print(str1)
输出结果:我叫oldboy,今年30岁
方式二:按索引传参
1
2str1 = '我叫{0},今年{1}岁'.format('oldboy',30)
print(str1)
输出结果:我叫oldboy,今年30岁
方式三:按key传参
1
2str1 = '我叫{name},今年{age}岁'.format(age=30,name='oldboy')
print(str1)
输出结果:我叫oldboy,今年30岁
16. count()
作用:count()主要作用是统计元素在字符串出现的次数。
1
2str1 = "oldboye"
print(str1.count(‘o’)) #统计字符o在字符串中出现的次数
数据结果:2