[英]find all words in list/file that begin/ends with a specific prefix/suffix
以下代碼給出了以特定前綴/后綴開頭/結尾的單詞。
string_list = [line.strip() for line in open("file.txt", 'r')]
for word in string_list:
if word[-1] == "a":
print word
string_list = [line.strip() for line in open("file.txt", 'r')]
for word in string_list:
if word[0] == "fi":
print word
我如何優化它以在海量數據上實現快速真實。 還有我如何通過像
python test.py --prefix fi
python test.py --suffix o
提前致謝。
如果word
是字符串,則word[0] == "fi"
不會執行您認為的操作。
您可以改為使用startswith
和endswith
檢查多字符后綴和前綴。
string_list = open("file.txt", 'r')
for word in string_list:
if word.startswith("fi") or word.endswith('a'):
print word
要將后綴/前綴作為參數傳遞給腳本,請看一下argparse
如果你需要的速度,你可以簡單地使用GREP ,這是寫在一個低級語言,勢必會比突飛猛進蟒蛇循環更快。
它也是可移植的,並且可以在Linux / Windows / OSX /上正常運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.