0

I wold like to expand acronyms in text file (e.g fyi--->for your information). I started by reading the acronyms file and store them in a dictionary as keys and values. Next, search each line in the text file for acronym(s) and expand them into complete phrase. After checking this post , I was able to read and create acronyms dictionary, but I have an issue with the replacement. The output file that should include the correct text is empty. here is my code and thanks in advance:

d = {}
with open('acronym.txt', 'r') as acronym:
for line in acronym:
    d[line.split(None, 1)[0]] = (line.split(None, 1)[1]).strip()

ntweetsfile= open('newTweets.txt', 'w')
import fileinput
for line in fileinput.input('tweets1k.txt', inplace=True):
    line = line.rstrip()
    if not line:
        continue
    for key in d:
        if str(key) in line:
            line = line.replace(str(key), d[key])
            ntweetsfile.write(str(line)+'\n')          
        else:
            ntweetsfile.write(str(line)+'\n')
ntweetsfile.close()
Ali Alwohaibi
  • 35
  • 1
  • 6
  • Are you sure that you're reading the input file correctly? What happens if you put a `print` statement where you replace the values? – roelofs Nov 22 '17 at 05:57
  • `fileinput.input('tweets1k.txt', inplace=True)` truncates the input file, which is probably not what you want. See the [note about `inplace`](https://docs.python.org/3/library/fileinput.html#fileinput.FileInput) in the docs. –  Nov 22 '17 at 06:00
  • roelofs, nothing is printed. I put print every where in the loop but nothing show up. – Ali Alwohaibi Nov 22 '17 at 06:08
  • Blurp, I tried this way: with open('tweets1k.txt', 'r') as infile: tweets = infile.readlines() - and -for line in tweets:- but did not work – Ali Alwohaibi Nov 22 '17 at 06:11
  • Is `tweets1k.txt` empty? –  Nov 22 '17 at 06:13
  • If nothing is printing, you're either not reading the file correctly, or you don't have permission to it (check that it opens ok), or it's empty. – roelofs Nov 22 '17 at 06:14
  • I would try to explicitly open it (like you do with acronym.txt), and see if you can read from it first. – roelofs Nov 22 '17 at 06:15
  • By the way, you don't need to do `str(key)` and `str(line)` everywhere you're doing that. It has no effect since `key` and `line` are already strings. –  Nov 22 '17 at 06:16
  • Blurp, You are right! the file was empty and I fix that. However, The output file looks away different than text file. Here is a sample: – Ali Alwohaibi Nov 22 '17 at 15:34
  • Original: They Don't Let Me Take A Nap Lol @ Empire State Building – Ali Alwohaibi Nov 22 '17 at 15:35
  • Output: thhew year oldu're welcome dee anw year oldu're welcomeI lato represenToiz a 304 w year oldu're welcomeou is a hoegh Liz a 304 w year oldu're welcomeou is a hoeckw year oldu're welcomelw year oldu're welcome noez Oh no! ato represenToiz a 304 .......etc (It seems mixing text togother) – Ali Alwohaibi Nov 22 '17 at 15:37

0 Answers0