導航:首頁 > 編程語言 > python整行替換

python整行替換

發布時間:2022-08-31 10:15:44

⑴ 如何只在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

閱讀全文

與python整行替換相關的資料

熱點內容
redhatlinux最新 瀏覽:177
python字典編程詞彙 瀏覽:144
微信和伺服器如何通訊 瀏覽:10
百家號伺服器配置有什麼用 瀏覽:598
怎麼為電腦加密 瀏覽:58
伺服器出現差錯是什麼意思 瀏覽:616
蘋果app移到商店裡怎麼刪掉 瀏覽:254
phpjsphtml 瀏覽:63
吃雞手機國際服伺服器超時怎麼辦 瀏覽:68
努比亞Z5無命令 瀏覽:642
展示網站雲伺服器 瀏覽:872
代碼混淆器php 瀏覽:366
貝恩pdf 瀏覽:208
丙烯pdf 瀏覽:367
雲伺服器華碩 瀏覽:713
sublime3運行python 瀏覽:191
怎麼把安卓視頻傳到蘋果上面 瀏覽:83
手機拍鬼片用什麼app 瀏覽:642
爬山虎app是干什麼用的 瀏覽:507
有哪些寫給程序員的歌 瀏覽:51