1
$\begingroup$

I have the following sample code.

StringSplit["a test string", " "]
Thread[WordData[%, "PartsOfSpeech"]]

The output I get is:

{a, test, string}
{{Noun, Preposition, Determiner}, {Noun, Verb}, {Noun, Verb}}

If I change "a test string" to "test string", then my code fails, giving the following:

{test, string}
{}

Can anyone tell me why this is and how to solve it?

$\endgroup$
3
$\begingroup$

Use Map, not Thread.

data = StringSplit["a test string"];
WordData[#, "PartsOfSpeech"] & /@ data
{{"Noun", "Preposition", "Determiner"}, {"Noun", "Verb"}, {"Noun", "Verb"}}
WordData[#, "PartsOfSpeech"] & /@ Rest @ data
{{"Noun", "Verb"}, {"Noun", "Verb"}}

The reason Thread doesn't work for {"test", "string"} is that WordData interprets a 1st argument that is a two element list as the form {<word>, <part-of-speech>} and returns { }, because "string" is not a part-of-speech. For a three-element or longer list it returns unevaluated, in which case, Thread can operate on it.

Edit

Pickett points out WordData will evaluate for some 1st arguments consisting of three element lists, but what is returned is still not an appropriate argument for Thread. For Thread to be applicable to this problem, the WordData expression given to it must be returned unevaluated. Therefore, I assert that it is not a good idea to use Thread for what the OP is trying to accomplish.

|improve this answer|||||
$\endgroup$
  • 1
    $\begingroup$ WordData[{"test", "Noun", "Run"}] evaluates. The third parameter is the "sense" of the word, so I don't understand why it evaluates for a list of three elements but not for two. $\endgroup$ – C. E. Aug 29 '14 at 15:03
  • 2
    $\begingroup$ @Pickett I think the third element has to be a valid sense tag, or WordData[..., "PartsOfSpeech"] returns unevaluated. Try WordData[{"test", "Noun", "run"}, "PartsOfSpeech"]. It is because WordData[{"a", "test", "string"}, "PartsOfSpeech"] returns unevaluated that Thread happens to work for the OP. $\endgroup$ – Michael E2 Aug 29 '14 at 15:36
  • $\begingroup$ @MichaelE2 Ah yes, I see now that that's how it works when you have PartsOfSpeech as the second argument. Without that it evaluates even with an invalid sense. Thanks for clarifying. +1 for this answer. $\endgroup$ – C. E. Aug 29 '14 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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