4
$\begingroup$

Say I have the function:

dep = TextStructure["He wrote a book. I read the book he wrote.", 
  "DependencyStrings", PerformanceGoal -> "Speed"]

Which outputs:

{"(wrote, 2)((nsubj, (He, 1)), (dobj, (book, 4)((det, (a, 3)))))", \
"(read, 2)((nsubj, (I, 1)), (dobj, (book, 4)((det, (the, 3)), (rcmod, \
(wrote, 6)((nsubj, (he, 5)))))))"}

Firstly, I want to extract each case of nsubj with the list:

{{"He"},{"I","he"}}

I have tried below but to no avail.

StringCases[dep, 
 Shortest["subj," ~~ __ ~~ 
    x : (LetterCharacter ~~ __ ~~ WordBoundary) /; x]]

This gets me half way, but it's not good enough:

StringCases[dep, Shortest["subj," ~~ __ ~~ ")"]]

Secondly, I want to get the root of the dependency which is the first word number pair of each sentence.

{{"wrote"},{"read"}}

If it were an expression it would be easy through:

Cases[dep, {s_Symbol, _Integer} :> ToString@s, 1]]

But I need to extract it from a string. Thanks in advance.

$\endgroup$

2 Answers 2

5
$\begingroup$

Try these:

StringCases[dep, 
 "((nsubj, (" ~~ w : WordCharacter .. ~~ ", " ~~ DigitCharacter .. ~~ "))" :> w]

StringCases[dep, "(" ~~ w : WordCharacter .. ~~ ___ :> w]
{{"He"}, {"I", "he"}}

{{"wrote"}, {"read"}}
$\endgroup$
2
$\begingroup$

A Regex attempt:

StringCases[#, 
  RegularExpression["[(]nsubj,\s+[(]([^,]+)"] :> "$1"]&/@dep

{{He}, {I, he}}

StringCases[#, 
  RegularExpression["^[(]([^,]+)"] :> "$1"]&/@dep

{{wrote}, {read}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.