Считать данные из текстового файла в массив ячеек - PullRequest
0 голосов
/ 21 июня 2020

У меня есть несколько текстовых файлов, содержащих данные в этом формате

File1.txt

subID    imageCondition  trial   textItem    imageFile   response    RT
Participant003   images  7   Is there a refrigerator?    07_targetPresent-refrigerator.jpg   z   1.436971
Participant003   images  6   Is there an oven mitt?  06_targetPresent-ovenmitt.jpg   z   0.519301
Participant003   images  1   Is there a toaster?     01_targetAbsent-toaster.jpg     m   1.110664
Participant003   images  3   Is there a wine bottle?     03_targetAbsent-winebottle.jpg  m   1.278945
Participant003   images  2   Is there a kettle?  02_targetAbsent-kettle.jpg  z   2.672123
Participant003   images  5   Is there a blender?     05_targetPresent-blender.jpg    m   2.633802
Participant003   images  8   Is there a bucket?  08_targetPresent-bucket.jpg     m   2.596154
Participant003   images  4   Is there a surf board?  04_targetAbsent-surfboard.jpg   m   1.072850

File2.txt

subID    imageCondition  trial   textItem    imageFile   response    RT
Participant005   images  1   Is there a toaster?     01_targetAbsent-toaster.jpg         0.000000
Participant005   images  2   Is there a kettle?  02_targetAbsent-kettle.jpg  m   8.213927
Participant005   images  6   Is there an oven mitt?  06_targetPresent-ovenmitt.jpg   z   3.569293
Participant005   images  4   Is there a surf board?  04_targetAbsent-surfboard.jpg       0.000000
Participant005   images  3   Is there a wine bottle?     03_targetAbsent-winebottle.jpg  m   8.538699
Participant005   images  7   Is there a refrigerator?    07_targetPresent-refrigerator.jpg   z   0.857319
Participant005   images  5   Is there a blender?     05_targetPresent-blender.jpg        0.000000
Participant005   images  8   Is there a bucket?  08_targetPresent-bucket.jpg     z   1.967220

Я хочу иметь возможность прочтите эти данные в массив ячеек, чтобы я мог индивидуально получить доступ к значениям, которые в нем присутствуют.

У меня есть следующий код, который я использую для чтения данных, но он не помогает, потому что я не могу хранить данные таким образом, чтобы я мог получить доступ к отдельным значениям. Например, мне нужны все значения из столбца «пробная версия» или «ответ».

function content = load_data(fileName)
fid = fopen(fileName,'r')
if fid > 0
   line_no =1;
   oneline{line_no} = fgetl(fid);
   while ischar(oneline{line_no})
      line_no = line_no +1;
      oneline{line_no} = fgetl(fid);
   endwhile
   fclose(fid)
   content = oneline;
endif
endfunction


for i= 1:size(txtFiles,2)
   data{i} = load_data(txtFiles{1,i});
end

for i=1:1:length(data)
   dataMat = cell2mat(data(i));
   for j=1:1:length(dataMat)
      line = dataMat{1,j};
      % Here I'm only able to fetch lines of data as strings that are separated by more than one space characters, making it more difficult access the required data 
   endfor            
endfor

Я ищу способ чтения этих данных из текстового файла в массив ячеек или матрица, чтобы я мог легко получить доступ к требуемым значениям, но я ограничен использованием традиционных методов импорта данных из текстового файла. Или, если бы я мог просто получить помощь с анализом данных таким образом, чтобы я мог получить доступ к тому, что требуется.

Примечание. Существует несколько подобных текстовых файлов. Также было бы очень полезно, если бы вы могли показать, как получить доступ к значениям в отдельных столбцах, например, в столбце «ответ».

1 Ответ

1 голос
/ 21 июня 2020

Это легко сделать с помощью чего-то вроде strsplit, чтобы разделить данные по пробелам; за исключением того, что в вашем поле textItem есть пробелы. Поэтому я бы предложил использовать регулярные выражения. Использование именованных токенов - удобный способ систематизировать результаты, когда вы ищете несколько отдельных частей одновременно. Я понимаю, что если вы не знакомы с регулярными выражениями, это непросто. Посетите regex101.com для получения информации и очень полезного онлайн-инструмента для проверки вашего регулярного выражения. См. this specifici c example на regex101. Тем не менее, вот мой ответ, который работает с вашими данными:

text = fileread(filename);
data = regexp(data,'^(?<subID>\w+)\s+(?<imageCondition>\w+)\s+(?<trial>\d+)\s+(?<textItem>.*?\?)\s+(?<imageFile>[-\.\w]+)\s+(?<response>\w)\s+(?<RT>[\d\.]+)','names','lineanchors')

Или вы можете превратить его в таблицу:

dataTable = struct2table(data)

Результат выглядит так:

      subID           imageCondition    trial              textItem                            imageFile                  response         RT     
__________________    ______________    _____    ____________________________    _____________________________________    ________    ____________

{'Participant003'}      {'images'}      {'7'}    {'Is there a refrigerator?'}    {'07_targetPresent-refrigerator.jpg'}     {'z'}      {'1.436971'}
{'Participant003'}      {'images'}      {'6'}    {'Is there an oven mitt?'  }    {'06_targetPresent-ovenmitt.jpg'    }     {'z'}      {'0.519301'}
{'Participant003'}      {'images'}      {'1'}    {'Is there a toaster?'     }    {'01_targetAbsent-toaster.jpg'      }     {'m'}      {'1.110664'}
{'Participant003'}      {'images'}      {'3'}    {'Is there a wine bottle?' }    {'03_targetAbsent-winebottle.jpg'   }     {'m'}      {'1.278945'}
{'Participant003'}      {'images'}      {'2'}    {'Is there a kettle?'      }    {'02_targetAbsent-kettle.jpg'       }     {'z'}      {'2.672123'}
{'Participant003'}      {'images'}      {'5'}    {'Is there a blender?'     }    {'05_targetPresent-blender.jpg'     }     {'m'}      {'2.633802'}
{'Participant003'}      {'images'}      {'8'}    {'Is there a bucket?'      }    {'08_targetPresent-bucket.jpg'      }     {'m'}      {'2.596154'}
{'Participant003'}      {'images'}      {'4'}    {'Is there a surf board?'  }    {'04_targetAbsent-surfboard.jpg'    }     {'m'}      {'1.072850'}

Если вы хотите превратить числовые поля c в числа:

dataTable.trial = str2double(dataTable.trial);
dataTable.RT = str2double(dataTable.RT);

Что тогда даст:

      subID           imageCondition    trial              textItem                            imageFile                  response      RT  
__________________    ______________    _____    ____________________________    _____________________________________    ________    ______

{'Participant003'}      {'images'}        7      {'Is there a refrigerator?'}    {'07_targetPresent-refrigerator.jpg'}     {'z'}       1.437
{'Participant003'}      {'images'}        6      {'Is there an oven mitt?'  }    {'06_targetPresent-ovenmitt.jpg'    }     {'z'}      0.5193
{'Participant003'}      {'images'}        1      {'Is there a toaster?'     }    {'01_targetAbsent-toaster.jpg'      }     {'m'}      1.1107
{'Participant003'}      {'images'}        3      {'Is there a wine bottle?' }    {'03_targetAbsent-winebottle.jpg'   }     {'m'}      1.2789
{'Participant003'}      {'images'}        2      {'Is there a kettle?'      }    {'02_targetAbsent-kettle.jpg'       }     {'z'}      2.6721
{'Participant003'}      {'images'}        5      {'Is there a blender?'     }    {'05_targetPresent-blender.jpg'     }     {'m'}      2.6338
{'Participant003'}      {'images'}        8      {'Is there a bucket?'      }    {'08_targetPresent-bucket.jpg'      }     {'m'}      2.5962
{'Participant003'}      {'images'}        4      {'Is there a surf board?'  }    {'04_targetAbsent-surfboard.jpg'    }     {'m'}      1.0729

Вы также спросили, как получить к нему доступ. Получите третий «ответ» из таблицы:

dataTable.response{3}

Или из структуры:

data(3).response
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...