1
$\begingroup$

I'm importing 100 of a specific file, whose format isn't supported by Mathematica. The file imports as a text file fine though by the below commands:

SetDirectory["MyFilepath here"];
MyFilenames = FileNames["*.fileextension"]
MyListofData = Import[#, {"Data"}] & /@ MyFilenames

The data imports like the following:

{{Some text here, more text, Word = 4590, More words},{Some text here, more text, Word = 381, More words},{Some text here, more text, Word = 2406, More words}...etc}

I need to extract the numbers follow "Word = ". I.e. to get {{4590},{381},{2406}}

I've tried a few different options listed by previous questions, but I'm stumped. Any help would be hugely appreciated.

$\endgroup$
6
  • $\begingroup$ How you can deal with this will depend on the details. Look at the FullForm. Is it: {"Some text here, more text, Word = 4590, More words"} or is it: {"Some text here", "more text", "Word = 4590", "More words"} Or is it importing in some other way? $\endgroup$
    – bill s
    Mar 13, 2023 at 19:01
  • $\begingroup$ It's importing like {{Some text here, more text, Word = 4590, More words},{Some text here, more text, Word = 381, More words}}, with no " " at all. $\endgroup$
    – Schaef
    Mar 13, 2023 at 19:05
  • 2
    $\begingroup$ Flatten[StringCases[#, DigitCharacter ..] & /@ text] $\endgroup$
    – Alan
    Mar 13, 2023 at 19:13
  • $\begingroup$ @Alan this worked thanks! There are multiple numbers in the list and I want the 2nd value from each data set, is that possible? $\endgroup$
    – Schaef
    Mar 13, 2023 at 20:26
  • 2
    $\begingroup$ If you can successfully import data, then include a representative sample of this data to get focused answers. Thanks. $\endgroup$
    – Syed
    Mar 13, 2023 at 20:44

1 Answer 1

1
$\begingroup$

Assuming that data consists of a list of lists of strings Like e.g.:

 dat = {{"Some text here", "more text", "Word=4590", 
    "More words"}, {"Some text here", "more text", "Word=381", 
    "More words"}, {"Some text here", "more text", "Word=2406", 
    "More words"}};

Then you may extract the number after "Word=" and change it into an integer by e.g.:

StringCases[#, 
    RegularExpression["Word=(\\d+)"] :> ToExpression["$1"]] & /@ 
  dat // Flatten

{4590, 381, 2406}

The "RegularExpression[..]" extracts the number as a string and ToExpression[..] changes it into an integer.

$\endgroup$
1
  • $\begingroup$ Unfortunately the data doesn't come out as strings so this wouldn't work, thanks though! $\endgroup$
    – Schaef
    Mar 13, 2023 at 20:27

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