我是python的新手。考虑我有一个列表['python','java','ruby']
我有一个文本文件:
jrubyk
knwdjavawe
weqkpythonqwe
1ruby.e
预期产出:
ruby
java
python
ruby
我需要打印隐藏在子列表中的列表中的字符串。 有没有办法获得它?
答案 0 :(得分:2)
当我想从较大的字符串中删除某些子字符串时,我倾向于使用regular expressions。这是一种不优雅但可读的方式。
import re
python_matcher = re.compile('python')
java_matcher = re.compile('java')
ruby_matcher = re.compile('ruby')
hidden_text_list = open('hidden.txt', 'r').readlines()
for line in hidden_text_list:
python_matched = python_matcher.search(line)
java_matched = java_matcher.search(line)
ruby_matched = ruby_matcher.search(line)
if python_matched:
print python_matched.group()
elif java_matched:
print java_matched.group()
elif ruby_matched:
print ruby_matched.group()
答案 1 :(得分:1)
蛮力方法是:
hidden_strings = ['python','java','ruby']
with open('path/to/textfile/as/in/example.txt') as infile:
for line in infile:
for hidden_string in hidden_strings:
if hidden_string in line:
print(hidden_string)