Python 查找列表/文件中以特定前缀/后缀开头/结尾的所有单词
下面的代码给出了以特定前缀/后缀开头/结尾的单词Python 查找列表/文件中以特定前缀/后缀开头/结尾的所有单词,python,regex,prefix,suffix,Python,Regex,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:
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
我如何优化它,以便在海量数据上实现真正的快速。
还有,我怎样才能通过param呢
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
要将后缀/前缀作为参数传递给脚本,请查看如果需要速度,只需使用,它是用低级语言编写的,肯定比python循环快得多
它也是可移植的,在Linux/Windows/OSX/…上运行得很好。看看是否可以传递参数。您可能想将此信息发布到。如何同时使用sys.argv[]和argparse?我将其更新为x=filter(lambda s:s.startswith(“fi”),string_list)如何同时使用sys.argv[]和argparse?grep可以更快,但是我想通过使用py足够快