I have text file in D drive named "data.txt". It have several columns and rows like
A B A B V B
B V A B A A
B B A A B A

I want to read it and then convert it to say A=1, B=2, V=3 and then write it so that it will be a array of number. how to do that?

Dani AI

Generated

Two realistic patterns are useful depending on whether the mapping is a small custom set (e.g. A=1, B=2, V=3 as in the original post) or a sequential alphabetic mapping (A→1, B→2, …). was right that translating while reading is efficient; noted a sequential approach but that method assumes contiguous uppercase letters. The items below preserve row boundaries, handle case and unknown tokens, and show both a C and a Python pattern for immediate reuse.

Recommended workflow: read the file line-by-line (keeps the grid), split by whitespace to get tokens, normalize each token to a single letter, map the letter via a lookup (explicit dict for custom mappings; programmatic table for A..Z), and write each numeric row out as whitespace-delimited text or as binary bytes if space/performance matters. Always cast chars to unsigned when indexing byte tables, and decide how to handle unknown symbols (map to 0, log an error, or abort).

/* C: line-by-line, lookup table approach (Windows paths shown) */
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void) {
    FILE *in = fopen("D:\\data.txt","r"), *out = fopen("D:\\data_nums.txt","w");
    if (!in || !out) return 1;
    int map[256]; for (int i=0;i<256;++i) map[i] = -1;
    map['A']=1; map['B']=2; map['V']=3; /* extend as needed or build programmatically */
    char line[1024];
    while (fgets(line, sizeof line, in)) {
        char *tok = strtok(line, " \t\r\n"); int first=1;
        while (tok) {
            unsigned char c = (unsigned char)toupper((unsigned char)tok[0]);
            int v = map[c] < 0 ? 0 : map[c];
            if (!first) fputc(' ', out);
            fprintf(out, "%d", v);
            first = 0;
            tok = strtok(NULL, " \t\r\n");
        }
        fputc('\n', out);
    }
    fclose(in); fclose(out);
    return 0;
}
# Python: explicit mapping (or create sequential mapping with enumerate)
mapping = {'A':1, 'B':2, 'V':3}            # custom mapping example
# mapping = {ch: i+1 for i,ch in enumerate("ABCDEFGHIJKLMNOPQRSTUVWXYZ")}  # sequential

with open(r"D:\data.txt") as fin, open(r"D:\data_nums.txt","w") as fout:
    for line in fin:
        nums = []
        for token in line.split():
            if not token: continue
            nums.append(str(mapping.get(token[0].upper(), 0)))   # unknown -> 0
        fout.write(" ".join(nums) + "\n")

Notes: choose text vs binary output based on downstream needs; stream-and-write (no full-file buffering) for large files; normalize case and validate tokens early. For custom mappings, keep the mapping table explicit so changes are clear; for full-alphabet conversions, programmatic mapping is concise.

Recommended Answers

All 3 Replies

These instructions assume you want to read it to memory and that the letters are being converted into numbers of equal size (1 byte):

  1. Open the file for reading
  2. Create a string array large enough to store the contents of the file.
  3. Iterate through each character of the file.
  4. Perform a translation using a switch before storing it into the array. Example:

    switch (inchar) {
        case 'A': memarray[i] = '1'; break;
        case 'B': memarray[i] = '2'; break;
        case 'V': memarray[i] = '3'; break;
    }
    

At that point you can do whatever you want with the string array. If you intended to save it to a new file it would be more efficient to write it directly into the file instead of saving it to memory. If you need to do something more useful than write it to the screen you may consider in your translation stage to organize your data into indexed structures, but since you didn't specify how you wanted to use this data there's no way I could recommend what that structure would be.

commented: I am not still getting it. I am sorry for asking you but can you write the code slightly so that i can have a better idea? +0

N1GHTS has giving you a good hint. That said, we don't do your homework for you... :-(

Member Avatar for Member #1042208

I think what he meant is, he is having several columns like he gave an example of.
If you want to do like this A -> 1, B -> 2, C -> 3 ....... Z -> 26, i.e sequentially. Then you should consider subtracting 64 from ASCII value of selected character. As 65 is ASCII of A, hence for A it will give you (65-64)=1. Similarly it will give for others as well.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.