如何将字母转换为带空格的数值并将其返回字母?

时间:2019-05-29 15:16:21

标签: matlab encoding

想使用诸如MATLAB中的快速傅里叶变换之类的数学技术将字母转换为数值并将其转换回字母。

示例:
以下是保存在“ text2figure.txt”文件中的文本

Hi how r u am fine take care of your health 
thank u very much
am 2.0

在MATLAB中阅读

data=fopen('text2figure.txt','r')
d=fscanf(data,'%s')
temp = fileread( 'text2figure.txt' ) 
temp = regexprep( temp, ' {6}', '   NaN' ) 
c=cellstr(temp(:))'

现在我希望将带有空格的单元格数组转换为数值/整数:

coding = 'abcdefghijklmnñopqrstuvwxyz .,;'
str = temp %// example text
[~, result] = ismember(str, coding)
y=result


result =

  Columns 1 through 18

     0     9    28     8    16    24    28    19    28    22    28     1    13    28     6     9    14     5

  Columns 19 through 36

    28    21     1    11     5    28     3     1    19     5    28    16     6    28    26    16    22    19

  Columns 37 through 54

    28     8     5     1    12    21     8    28     0     0    21     8     1    14    11    28    22    28

  Columns 55 through 71

    23     5    19    26    28    13    22     3     8     0     0     1    13    28     0    29     0

现在我希望将数值转换回字母:

Hi how r u am fine take care of your health 
thank u very much
am 2.0

如何编写MATLAB代码以将变量result中的数值返回字母?

1 个答案:

答案 0 :(得分:0)

问题中的大多数代码没有任何有用的效果。这三行是导致result的行:

str = fileread('test2figure.txt');
coding = 'abcdefghijklmnñopqrstuvwxyz .,;';
[~, result] = ismember(str, coding);

ismember在第二个输出参数中返回coding中每个元素到str中的索引。因此,result是我们可以用来索引到coding的索引:

out = coding(result);

但是,由于str的某些元素未在coding中出现,并且对于这些元素,ismember返回0,这不是有效的索引,因此此方法不起作用。我们可以用新字符替换零:

coding = ['*',coding];
out = coding(result+1);

基本上,我们将每个代码都移一个,为1添加一个新代码。

我们在这里缺少的字符之一是换行符。因此,三行已变成一行。您可以通过将换行符添加到coding表中来为其添加代码:

str = fileread('test2figure.txt');
coding = ['abcdefghijklmnñopqrstuvwxyz .,;',char(10)]; % char(10) is the newline character
[~, result] = ismember(str, coding);

coding = ['*',coding];
out = coding(result+1);

使用ASCII码表,所有这些都更容易实现:

str = fileread('test2figure.txt');
result = double(str);

out = char(result);