Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找列表/文件中以特定前缀/后缀开头/结尾的所有单词_Python_Regex_Prefix_Suffix - Fatal编程技术网

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足够快