#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    1
    Rep Power
    0

    Opening text file, converting one four letter word to another


    I am trying to open a saved text file that has a short sentence in it and then convert all four letter words in the sentence to "XXXX". Then save it back to the file. So far I am struggling with this. I pasted what I have done so far, but seem to be stuck now. I'm not sure what is wrong with what I have or if I am just missing something. Also I am new to the forum so if someone can tell me how to post my program properly, I will fix it. Any help would be greatly appreciated!



    def censor():
    filename = input("Enter name of file: ")
    file = open(filename, 'r+')
    i = 0
    alist = []
    for element in file:
    words = element.split()
    for i in range(len(words)):
    if len(words[i]) == 4:
    element.replace(words, "XXXX")
    i = i+1
    alist.append(newwords)
    else:
    alist.append(words)
    print (alist)
    file.close()
    file1 = open(filename, 'w')
    for element in alist:
    file.write(alist)
    file.close()
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,851
    Rep Power
    481
    I'd write the program with flex.

    I did not test your program. I'd guess that
    1) you have trouble identifying 4 letter words. Your program would remove "cat." from "I ate my cat."
    2) You have trouble reconstructing the original.

    If I had to use python I'd use the regular expression package,
    import re
    With flex I'd also use regular expressions---it's so much easier.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    1
    Rep Power
    0
    Hi Ted,

    I have done something similar with Python using regex. I have popped my code below.

    Code:
    import re
     
    file = open("C:\\test.txt", 'r+')
    x = file.readlines()
    x = str(x)
    
    foo = re.compile(r"""aaaaa""", re.IGNORECASE)
    bar = foo.sub('bbbbb', x)
    print bar
    To format your code snippets you just need to highlight the text and click the # button which will wrap you selection with [CODE] tags.

    Quick note - building regex patterns can be rather daunting so I find it helpful to use a piece of open source software called Kodos which you can find http://kodos.sourceforge.net/.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Location
    Texas
    Posts
    24
    Rep Power
    0
    I think this line is the problem:

    element.replace(words, "XXXX")

    Try changing that to:

    element.replace(words[i], "XXXX")

IMN logo majestic logo threadwatch logo seochat tools logo