我正在编写一个程序,其中我必须检查地址集中的所有地址是否都包含特定的关键字-Word:
例如A:
设置组地址“ Private-MT”“ ABCD45-48 / 70-71”
设置组地址“ Private-MT”“ ABCD45-48 / 70-71”添加“ ABCD47”
设置组地址“ Private-MT”“ ABCD45-48 / 70-71”添加“ ABCD48”
设置组地址“ Private-MT”“ ABCD45-48 / 70-71”添加“ ABCD70”
设置组地址“ Private-MT”“ ABCD45-48 / 70-71”添加“ ABCD71”
例如B:
设置组地址“ Private-MT”“ ABCD45-48 / XYCD70-71”
设置组地址“ Private-MT”“ ABCD45-48 / XYCD70-71”添加“ ABCD47”
设置组地址“ Private-MT”“ ABCD45-48 / XYCD70-71”添加“ ABCD48”
设置组地址“ Private-MT”“ ABCD45-48 / XYCD70-71”添加“ XYCD70”
设置组地址“ Private-MT”“ ABCD45-48 / XYCD70-71”添加“ XYCD71”
在此示例中,地址集名称为“ ABCD45-48 / 70-71”,因此在我完全删除该地址集之前,我需要检查该地址集的所有成员的名称中都必须包含ABCD 。
如果它们的名称中都包含ABCD,则删除整个地址集
A的输出:
未设置组地址“ Private-MT”“ ABCD45-48 / 70-71”
否则删除特定行。
B的输出:
未设置组地址“ Private-MT”“ ABCD45-48 / XYCD70-71”添加“ ABCD47”
未设置组地址“ Private-MT”“ ABCD45-48 / XYCD70-71”添加“ ABCD48”
答案 0 :(得分:1)
您的问题尚不清楚,但是我会在标题中询问您的问题。如果您有字符串,并且想搜索子字符串,则只能使用
if substring in string:
#do what you want to do
另一种方法是使用正则表达式,这里的文档re python
下次请分享您的脚本,以帮助所有人了解您的问题;)
编辑
filename = "test.text"
import re
def splitAddresses(data):
addresses=[]
l=[]
pattern=re.compile("^[GROUP]+[0-9]+[:]$")
for element in data:
isAmatch=pattern.match(element)
if isAmatch==None:
l.append(element)
else:
addresses.append(l)
l=[]
addresses.append(l)
return(addresses[1:])
def parseAddress():
with open(filename) as f:
data = f.readlines()
addresses=splitAddresses(data)
for element in addresses:
prefix=element[0][32:36]
length_data=len(element)
for address in element[1:]:
if address.count(prefix)!=2:
element.remove(address)
new_length = len(element)
if new_length==length_data:
print(element[0])
else:
print(element[1:])
parseAddress()
尝试过此文件
GROUP1:
set group address "Private-MT" "ABCD45-48/70-71"
set group address "Private-MT" "ABCD45-48/70-71" add "ABCD47"
set group address "Private-MT" "ABCD45-48/70-71" add "ABCD48"
set group address "Private-MT" "ABCD45-48/70-71" add "ABCD70"
set group address "Private-MT" "ABCD45-48/70-71" add "ABCD71"
GROUP2:
set group address "Private-MT" "ABCD45-48/70-71"
set group address "Private-MT" "ABCD45-48/70-71" add "ABCD47"
set group address "Private-MT" "ABCD45-48/70-71" add "ABCD48"
set group address "Private-MT" "ABCD45-48/70-71" add "XYCD70"
set group address "Private-MT" "ABCD45-48/70-71" add "XYCD71"
输出为:
set group address "Private-MT" "ABCD45-48/70-71"
['set group address "Private-MT" "ABCD45-48/70-71" add "ABCD47"\n', 'set group address "Private-MT" "ABCD45-48/70-71" add "ABCD48"\n']
您可以编辑脚本并存储信息,因为我进行了打印以显示效果;)