0

I have 2 txt files (a and b_).

file_a.txt contains a long list of 4-letter combinations (one combination per line):

aaaa
bcsg
aacd
gdee
aadw
hwer
etc.

file_b.txt contains a list of letter combinations of various length (some with spaces):

aaaibjkes
aaleoslk
abaaaalkjel
bcsgiweyoieotpwe
csseiolskj
gaelsi asdas
aaaloiersaaageehikjaaa
hwesdaaadf wiibhuehu
bcspwiopiejowih
gdeaes
aaailoiuwegoiglkjaaake
etc.

I am looking for a python script that would allow me to do the following:

  1. read file_a.txt line by line
  2. take each 4-letter combination (e.g. aaai)
  3. read file_b.txt and find all the various-length letter combinations starting with the 4-letter combination (eg. aaaibjkes, aaailoiersaaageehikjaaa, aaailoiuwegoiglkjaaaike etc.)
  4. print the results of each search in a separate txt file named with the 4-letter combination.

File aaai.txt:

aaaibjkes 
aaailoiersaaageehikjaaa
aaailoiuwegoiglkjaaake
etc.

File bcsi.txt:

bcspwiopiejowih
bcsiweyoieotpwe
etc.

I'm sorry I'm a newbie. Can someone point me in the right direction, please. So far I've got only:

#I presume I will have to use regex at some point
import re

file1 = open('file_a.txt', 'r').readlines()
file2 = open('file_b.txt', 'r').readlines()

#Should I look into findall()?
2
  • I don't think this question has anything to do with combinations. When we talk about combinations, we talk about the different ways to form a string. Such as a combination of a, b, c of length 2 would look like ab bc, ca` May 30, 2016 at 10:54
  • Thanks. Shall we call them "strings", then. All the entries in file_a.txt and file_b.txt? May 30, 2016 at 14:57

3 Answers 3

1

I hope this would help you;

file1 = open('file_a.txt', 'r')
file2 = open('file_b.txt', 'r')

#get every item in your second file into a list 
mylist = file2.readlines()

# read each line in the first file
while file1.readline():
    searchStr = file1.readline()
    # find this line in your second file
    exists = [s for s in mylist if searchStr in s]
    if (exists):
        # if this line exists in your second file then create a file for it
        fileNew = open(searchStr,'w')
        for line in exists:
            fileNew.write(line)

        fileNew.close()

    file1.close()
2
  • Cheers! It doesn't work, though. There seems to be the following error: mylist = file2.readlines() AttributeError: 'list' object has no attribute 'deadlines' Any ideas how to fix it? May 31, 2016 at 0:29
  • @jigitjigit2 is it a typo or did you put 'deadlines' with a d in your code ? If you paste erolkaya84's code it won't work if you don't open the file first, i'll try to edit his post May 31, 2016 at 6:02
0

What you can do is to open both files and run both files down line by line using for loops.

You can have two for loops, the first one reading file_a.txt as you will be reading through it only once. The second will read through file_b.txt and look for the string at the start.

To do so, you will have to use .find() to search for the string. Since it is at the start, the value should be 0.

file_a = open("file_a.txt", "r")
file_b = open("file_b.txt", "r")

for a_line in file_a:
    # This result value will be written into your new file
    result = ""
    # This is what we will search with
    search_val = a_line.strip("\n")
    print "---- Using " + search_val + " from file_a to search. ----"
    for b_line in file_b:
        print "Searching file_b using " + b_line.strip("\n")
        if b_line.strip("\n").find(search_val) == 0:
            result += (b_line)
    print "---- Search ended ----"
    # Set the read pointer to the start of the file again
    file_b.seek(0, 0)

    if result:
        # Write the contents of "results" into a file with the name of "search_val"
        with open(search_val + ".txt", "a") as f:
            f.write(result)

file_a.close()
file_b.close()

Test Cases:

I am using the test cases in your question:

file_a.txt

aaaa
bcsg
aacd
gdee
aadw
hwer

file_b.txt

aaaibjkes
aaleoslk
abaaaalkjel
bcsgiweyoieotpwe
csseiolskj
gaelsi asdas
aaaloiersaaageehikjaaa
hwesdaaadf wiibhuehu
bcspwiopiejowih
gdeaes
aaailoiuwegoiglkjaaake

The program produces an output file bcsg.txt as it is supposed to with bcsgiweyoieotpwe inside.

7
  • That's right. My apologies for not being precise in my previous comment. "bcsgiweyoieotpwe" is the only matching string in this sample. But why does the program create zero-byte txt files for strings from file_a.txt without matches in file_b.txt? Thanks again! May 31, 2016 at 5:19
  • @jigitjigit2 My previous code did that, I just wrote to a new file even when there are no matches. I edited such that it won't do that anymore. May 31, 2016 at 5:21
  • Fantastic! It works! That's exactly it. Is there any simple way of making the program show the stream of currently read and matched strings? (original file_a and file_b are very long and it would be nice to know where we are in the process. As it is now when I am running the script on these big txt files, I only know that the script is running by watching the use of CPU by Python in system monitor. I cannot see any new text files being created. Perhaps because there is going to be so many of them). Cheers! May 31, 2016 at 5:55
  • @jigitjigit2 as in print out what it is currently doing? May 31, 2016 at 5:56
  • It works when I try it on shorter versions of my original text files. But when I use the big txt files it does not seem to be doing anything. There are no new txt files in the directory. Is there a limit on the number of lines in text files being processed? May 31, 2016 at 6:03
0

Try this:

f1 = open("a.txt","r").readlines()
f2 = open("b.txt","r").readlines()
file1 = [word.replace("\n","") for word in f1]
file2 = [word.replace("\n","") for word in f2]

data = []
data_dict ={}
for short_word in file1:
    data += ([[short_word,w] for w in file2 if w.startswith(short_word)])

for single_data in data:
    if single_data[0] in data_dict:
        data_dict[single_data[0]].append(single_data[1])
    else:
        data_dict[single_data[0]]=[single_data[1]]

for key,val in data_dict.iteritems():
    open(key+".txt","w").writelines("\n".join(val))
    print(key + ".txt created")
3
  • Thank you. The script runs and produces no error messages but it doesn't work, i.e. it doesn't create any new txt files. Any ideas how to fix it? May 31, 2016 at 0:32
  • In my case aaai.txt and bcsg.txt are created. May 31, 2016 at 5:37
  • Apologies. It works! It just took a little longer probably due to the large size of my original text files. Thank you very much May 31, 2016 at 7:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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