Why replacing strings from dictionary produce empty file

Related searches

I'm trying to replace some strings with other strings in a text file, but the code produce empty file (file size is 0)

what am I missing ?

emotion_list = {":-)" : "happy-similey", \
                ":-(": "sad-similey"}

for line in fileinput.input(file_name, inplace=True):
    if not line:
        continue
    for f_key, f_value in emotion_list.items():
        if f_key in line:
            line = line.replace(f_key, f_value)

You missing the print statement to send replaced line to your file:

for line in fileinput.input(file_name, inplace=True):

    if not line:
        continue
    for f_key, f_value in emotion_list.items():
        if f_key in line:
            line = line.replace(f_key, f_value)

    print(line, end="") # print without newline

6. Dictionaries, sets, files, and modules — Beginning Python , The empty dictionary is denoted with a pair of curly braces, {} : > To make data available the next time you turn on your computer and start your program, calls to write will usually be replaced by a loop that writes many more lines into the file. So this is a dictionary problem, I have no problem with the json itself. I cannot control which fields are in my input, so one file may have field1 and field2 . The next could have all three, or only one.

In your code you are maching file line with word.So split line by spaces to get words (If you do match word in a entire line then you have to give the no.of occurences you want to replace and no of occurences is dynamic.You don't how much occurences would be there in file in a real scenarios)

emotion_list = {":-)" : "happy-similey", \
                ":-(": "sad-similey"}


file="I am not really :-) but I am not :-( too "

for line in file.split(): 
    for f_key, f_value in emotion_list.items():
        if f_key == line:            
            file=file.replace(line, f_value,1)

print(file)

output

I am not really happy-similey but I am not sad-similey too 

Ch.6: Dictionaries and strings, The main focus in the course is on working with files, dictionaries and strings. t1 = temps >>> t1['Stockholm'] = 10.0 # change t1 >>> temps # temps is also initialize a dictionary with the property names as keys and empty dictionaries {} as in a dictionary (key is company); make a function for reading one company's file. Assuming a following text file (dict.txt) is present. 1 aaa 2 bbb 3 ccc. Following Python code reads the file using open() function. Each line as string is split at space character.

This is basically the problem you are facing:

lst = ["abc", "acd", "ade"]

for x in lst:
  x = x.replace("a", "x")

print(lst) # ["abc", "acd", "ade"]

Instead, you should replace the ith element of the list:

lst = ["abc", "acd", "ade"]

for i, x in enumerate(lst):
  lst[i] = x.replace("a", "x")

print(lst) # ['xbc', 'xcd', 'xde']

This is happening because strings are immutable in Python!

Python Dict and File | Python Education, Can build up a dict by starting with the the empty dict {} operator works conveniently to substitute values from a dict into a string by name:. Dictionary in python is a very useful data structure and at many times we see problems regarding converting a string to a dictionary. So, let us discuss how we can tackle this problem. Method # 1: Using eval()

Python Dictionary, Check out what is a dictionary in Python, how to create, append, update, and delete But the keys have a constraint to be of any immutable data types such as a string, Define a blank dictionary with no elements blank_dict = {} # Define a Traceback (most recent call last): File "C:/Python/Python35/test_dict.py", line 2,� Creating Empty Dictionary. We can create an empty dictionary in 2 ways i.e. ''' Creating empty Dictionary ''' # Creating an empty dict using empty brackets wordFrequency = {} # Creating an empty dict using dict() wordFrequency = dict() It will create an empty dictionary like this, {} Creating Dictionaries with literals

Using dictionaries to store data as key-value pairs, An empty dictionary can be initialized by either using the dict() constructor most part, we'll find ourselves using strings as keys when manually creating dictionary will return a text file (in JSON format) that can be turned into a Python dictionary : by reference, including the ability to change the values that are referred to: How to Create an Empty Dictionary in Python. In this article, we show how to create an empty dictionary in Python. A dictionary in Python is really an associative array or hash table that is composed of key-value pairs. So if you have a dictionary called itemprices, one key may be "T-shirt" with a value of 24.95, another key may be "Brief" with a value of 14.95, a

The key is handled in a case-insensitive manner; it is translated to lowercase before it is used with the string dictionary. In .NET Framework version 1.0, this class uses culture-sensitive string comparisons. However, in .NET Framework version 1.1 and later, this class uses CultureInfo.InvariantCulture when comparing strings.

Comments
  • show the content of file_name