I have a file which has many line, and I want to extract these info in a list = ['sheep','cow','buffalo']
animal wild -list {
tiger lion hyena
}
aaaa
bbbb
cccc
animal domesticated_0 -list {
sheep
}
dddd
animal domesticated_1 -list {
cow buffalo
}
eeee
I am using the code below but it is far from what I wanted.
temp_list = ['domesticated_0','domesticated_1']
start = False
for i in temp_list:
for line in file:
if start:
f1.write(line)
if li.endswith("}"):
start = False
elif not li.startswith("animal"):
start = False
elif li.startswith("animal") and i in line:
f1.write(line)
start = True
if li.endswith("}"):
start = False
This solutions uses a regular expression:
(?:\banimal\s+domesticated_[01]\s+-list\s+{\s*)((?:\b\w+\b(?:\s*))+)(?:})
(?:\banimal\s+domesticated_[01]\s+-list\s+{\s*)
matches animal
on a word boundary followed by one or more spaces followed by domesticated_
followed by either a 0
or 1
followed by one or more spaces followed by -list
followed by one or more spaces followed by {
followed by 0 or mores spaces, all in a non-capturing group. ((?:\b\w+\b(?:\s*))+)
matches 1 or more occurrences of a word on a word boundary followed by 0 or more spaces (Group 1). (?:})
matches }
in a non-capturing group. After a string of animals is captured by the above regex, for example 'cow bufallow '
, trailing spaces are removed and the string is split on spaces and appended to a list of animals:
The code:
import re
text = """
animal wild -list {
tiger
lion
hyena
}
aaaa
bbbb
cccc
animal domesticated_0 -list {sheep}
dddd
animal domesticated_1 -list {
cow
buffalo
}
eeee """
animals = []
for m in re.finditer(r'(?:\banimal\s+domesticated_[01]\s+-list\s+{\s*)((?:\b\w+\b(?:\s*))+)(?:})', text):
animals.extend(re.split(r'\s+', m.group(1).strip()))
print(animals)
Prints:
['sheep', 'cow', 'buffalo']
You can and should replace the regex with:
(?:\banimal\s+domesticated_\d+\s+-list\s+{\s*)((?:\b\w+\b(?:\s*))+)(?:})
if domesticated_
can be followed by any number besides 0
and 1
.
This sounds like a job for regular expressions to me.
I would do something like this:
# Example of input
txt = """
animal wild -list {
tiger
lion
hyena
}
aaaa
bbbb
cccc
animal domesticated_0 -list {sheep}
dddd
animal domesticated_1 -list {
cow
buffalo
}
eeee
"""
import re
animals = re.findall("animal\s+domesticated_\d\s+-list\s+[{]\s*([^},]+)+\s*[}]", txt)
animals = [a.strip() for a in "\n".join(animals).split("\n") if len(a.strip()) > 0]
print(animals)
The code above outputs: ['sheep', 'cow', 'buffalo']
I just did a brute force solution without using regex
a="""animal wild -list {
tiger
lion
hyena
}
aaaa
bbbb
cccc
animal domesticated_0 -list {sheep}
dddd
animal domesticated_1 -list {
cow
buffalo
}
eeee """
temp_list = ['domesticated_0','domesticated_1']
output = []
def getcontent(index,content):
temp_answer = []
while(index < len(content)):
temp_answer.append(content[index])
if '}' in content[index]:
break
index+=1
answerwithbrackets = ''.join(temp_answer)
index1=answerwithbrackets.index('{')
index2=answerwithbrackets.index("}")
return [answerwithbrackets[index1 + 1:index2 ].split(),index]
index =0
content = a.split('\n')
while (index < len(content)):
for word in temp_list:
if word in content[index]:
tempoutput =getcontent(index,content)
index = tempoutput[1]
output.extend(tempoutput[0])
index+=1
print(output)
OUTPUT
['sheep', 'cow', 'buffalo']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.