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
單詞數組的文本形式: