Extracting specific information from data
<p>How can i convert a data format like: </p>

<pre><code>James Smith was born on November 17, 1948
</code></pre>

<p>into something like </p>

<pre><code>("James Smith", DOB, "November 17, 1948")
</code></pre>

<p>without having to rely on positional index of strings</p>

<p>I have tried the following </p>

<pre><code>from nltk import word_tokenize, pos_tag

new = "James Smith was born on November 17, 1948"
sentences = word_tokenize(new)
sentences = pos_tag(sentences)
grammar = "Chunk: {&lt;NNP*&gt;&lt;NNP*&gt;}"
cp = nltk.RegexpParser(grammar)
result = cp.parse(sentences)
print(result)
</code></pre>

<p>How to proceed further to get the output in desired fromat.</p>

<p>You could always use a regular expressions.
The regex <code>(\S+)\s(\S+)\s\bwas born on\b\s(\S+)\s(\S+),\s(\S+)</code> will match and return data from specifically the string format above.</p>

<p>Here's it in action: <a href="https://regex101.com/r/W2ykKS/1" rel="nofollow">https://regex101.com/r/W2ykKS/1</a></p>

<p>Regex in python:</p>

<pre><code>import re

regex = r"(\S+)\s(\S+)\s\bwas born on\b\s(\S+)\s(\S+),\s(\S+)"
test_str = "James Smith was born on November 17, 1948"

matches = re.search(regex, test_str)

# group 0 in a regex is the input string

print(matches.group(1)) # James
print(matches.group(2)) # Smith
print(matches.group(3)) # November
print(matches.group(4)) # 17
print(matches.group(5)) # 1948
</code></pre>

python python-3.x nltk stanford-nlp information-retrieval