简体   繁体   中英

How to append strings specified in the text file to the end of every following line?

The text file is:

ar
abcd
ak
abcd
efgh
tx
abcd

I would like to end up with something like:

abcd, ar
abcd, ak
efgh, ak
abcd, tx

I have this code:

    file_name1 = "file1.txt"
    file_name2 = "file2.txt"

    with open(file_name2, 'w') as out_file:
        with open(file_name1, 'r') as in_file:
            for line in in_file:
                if len(line) == 3:
                    out_file.write(line.rstrip('\n') + line + '\n')

However, this appends the same line to any line that's length 2 (+ \\n).

Loop over the lines and save the last 2-letter line you see, and update it every time you encounter a 2-letter line. For other lines, prepend it with the last line you saved.

with open('source.txt') as source, open('dest.txt', 'w') as dest:
    last_two_lettered_line = None
    for line in source:
        line = line.strip()
        if not line:
            continue
        if len(line) == 2:
            last_two_lettered_line = line
            continue
        if not last_two_lettered_line:
            continue
        modified = '{line}, {two}'.format(line=line, two=last_two_lettered_line)
        dest.write(modified + '\n')

which gives you:

abcd, ar
abcd, ak
efgh, ak
abcd, tx

The main problem in your text file is the '\\n' in empty lines, then the next problem you had is that you are notice only to words in length of 3.

You can use this code to make it by the word number, if you are keeping this format, if you want to do the same but you want to make the term under word length, you may change it:

file_name1 = "file1.txt"
file_name2 = "file2.txt"

word_count = 0
with open(file_name2, 'w') as out_file:
    with open(file_name1, 'r') as in_file:
        for str in in_file:
            if (str != '\n'):
                word_count += 1
                if word_count % 2 == 1:
                    prev = str
                elif word_count % 2 == 0:
                    out_file.write(str.rstrip('\n') + ',' + prev)

You must clarify what the term is, to make it right. (Since if the term is that only second word will be attach before the last one, it work's)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM