乙個python文件字串處理小例子

2021-08-03 07:30:37 字數 1381 閱讀 5664

我從網上找的計算機英語檔案內容是這樣的:

需要寫乙個小指令碼,把圖2處理成圖1那樣的格式,我用了2種方法。

第一種:

#-*-coding:utf-8-*- __author__ = 'administrator' import codecs indata=codecs.open("cs_english.txt", 'r+', 'utf-8').read() to_file="copy2.txt" with open(to_file,'w+') as file:
#通過"\n"用split擷取的行組成乙個列表lines

lines=indata.split('\n')

words=

#line="6. if conj. 如果 "

for line in lines:

#以空白為切點,將一行切2刀,成3段,組成列表w

w=line.split(none,2)

#如果列表數量大於2,,選取第2個元素,賦值給word

if len(w)>2:

word=w[1]

outdata='\n'.join(words)

file.write(outdata)

第二種:
# -*-coding:utf-8-*-

import re

__author__ = 'administrator'

#2. command n. 命令,指令

#3. use v. 使用,用途

indata = open("cs_english.txt", 'r', encoding='utf-8').read()

#使用正規表示式,選取至少2個單詞,全為英語的字串,組成字母字串列表 d

d = re.findall('[a-za-z]', indata)

#使用join,把d列表變成圖1的形式
outdata='\n'.join(d)

out_file=open("copy3.txt",'w+')

out_file.write(outdata)

Python 文件化字串

python有乙個很奇妙的特性,稱為 文件字串 它通常被簡稱為 docstrings docstrings是乙個重要的工具,由於它幫助你的程式文件更加簡單易懂,你應該盡量使用它。你甚至可以在程式執行的時候,從函式恢復文件字串!usr bin python filename func doc.py d...

python之文件字串

程式的可讀性最重要。一般建議在函式體開始的部分新增注釋。通過呼叫help 函式名.doc 可以檢視注釋。測試文件字串基本用法 defprintmax a,b 用於比較兩個數的大小,列印較大的值 if a b print a,是較小值 if aprint b,較大值 printmax 11,22 he...

Python 字串處理

python endswith 方法用於判斷字串是否以指定字尾結尾,如果以指定字尾結尾返回 true 否則返回 false 可選引數 start 與 end 為檢索字串的開始與結束位置。語法 endswith 方法語法 str.endswith suffix start end 引數 返回值 如果字...