Python文本替換(剔除、截取、添加字符串)


1. 刪除字符串中的數字
要將以下文件中的數字和描述刪除,只留下單詞,並且轉存爲Objective-C的數組格式,第一步,先將數字全部剔除:
這裏寫圖片描述

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import re

file = open("words.txt")
output = open("out.txt", 'wb')

for line in file.readlines():
    #刪除字母、‘,’、‘()’、‘tab’以外的字符,即數字
    newline = filter(lambda ch: ch in ' abcdefghijklmnopqrstuvwxyz,() ', line)
    print newline
    output.write('@"' + newline + '\n')
file.close()
output.close()

處理完之後,得到一下文本文件:
這裏寫圖片描述
2. 剔除單詞後邊所有字符串

#!/usr/bin/python
# -*- coding: UTF-8 -*-

file = open("out.txt", 'r')
output = open("dict.txt", "wb")

for line in file.readlines():
    #查找單詞後頭的tab,記錄偏移量
    pos = line.find("   ", 0)
    print line[0:pos] + '", '
    #將tab之前的字符串,加上引號、逗號和換行符,寫入數出文件
    output.write(line[0:pos] + '", \n')
file.close()
out.close()

得到最終我們需要的Objective-C單詞數組的文本形式:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章