Jump to content

[PYTHON] Not sure if possible, but how to convert a string into an integer code?

CandleJakk

Hi guys, what I'm trying to do is make a program that would convert words in a string into numbers, here is an example of it in action:

wordreplace("Hi hey hello hey hi hello")

returns

1 2 3 2 1 3

Here is my current code, which isn't anywhere near functional:

def wordreplace(aString):
    aString = aString.lower()
    aString = aString.split()
    b = [(i+1, x) for i, x in enumerate(aString)]
    return b

I had another updated version using some different syntax' e.g. globals etc. but it ended up doing the same as this piece, so I'd be glad for anyone to shed some light on how I could pull this off. Please feel free to ask any questions about what I'm trying to do if it wasn't clear.

 

Thanks! :)

Link to comment
Share on other sites

Link to post
Share on other sites

There could be a better way of doing this, but perhaps you could use a dictionary to map your integer values to your keywords (e.g. hi -> 1, hey -> 2, etc.)

 

Then once you've done that, you loop through your input string and look up each split value for a corresponding key in that dictionary.

 

Slightly misunderstood what you were asking, mathijs's answer seems good to me.

CPU: i7-4790K --- HEATSINK: NZXT Kraken X61 --- MOBO: Asus Z97-A --- GPU: GTX 970 Strix --- RAM: 16GB ADATA XPG --- SSD: 512GB MX100 | 256GB BX200 HDD: 1TB WD Black --- PSU: EVGA SuperNova G2 --- CASE: NZXT H440 --- DISPLAY3 x Dell U2414H --- KEYBOARD: Pok3r (Clears) --- MOUSE: Logitech G Pro --- OS: Windows 10

Link to comment
Share on other sites

Link to post
Share on other sites

The first part is good.

Iterate through the words and keep a dictionary  and a counter.

For every word look up if it is in the dictionary.

If it is not in the dictionary, add it with the counter as value. Increase the counter by one.

If it is in the dictionary, use the value associated with it.

Since im on my phone I cant program it out right now (I have a bussy day today, srry)

Desktop: Intel i9-10850K (R9 3900X died 😢 )| MSI Z490 Tomahawk | RTX 2080 (borrowed from work) - MSI GTX 1080 | 64GB 3600MHz CL16 memory | Corsair H100i (NF-F12 fans) | Samsung 970 EVO 512GB | Intel 665p 2TB | Samsung 830 256GB| 3TB HDD | Corsair 450D | Corsair RM550x | MG279Q

Laptop: Surface Pro 7 (i5, 16GB RAM, 256GB SSD)

Console: PlayStation 4 Pro

Link to comment
Share on other sites

Link to post
Share on other sites

15 minutes ago, spenser_l said:

There could be a better way of doing this, but perhaps you could use a dictionary to map your integer values to your keywords (e.g. hi -> 1, hey -> 2, etc.)

 

Then once you've done that, you loop through your input string and look up each split value for a corresponding key in that dictionary.

 

Slightly misunderstood what you were asking, mathijs's answer seems good to me.

Ok, thanks for your reply though! :)

Link to comment
Share on other sites

Link to post
Share on other sites

15 minutes ago, mathijs727 said:

The first part is good.

Iterate through the words and keep a dictionary  and a counter.

For every word look up if it is in the dictionary.

If it is not in the dictionary, add it with the counter as value. Increase the counter by one.

If it is in the dictionary, use the value associated with it.

Since im on my phone I cant program it out right now (I have a bussy day today, srry)

I see, thanks! I'll try this later. Have a good day!

Link to comment
Share on other sites

Link to post
Share on other sites

I don't understand how you got the number in the example from that string, could you explain the relation?

 

Edit: never mind worked it out :P

 

edit 2: Just to clarify you want it so it records the position of the first 'hi' then next time it sees that word it displays' the first position it was found?

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

If i got it correctly this should do what you want:

def wordreplace(text):
    words = text.lower().split(' ')

    result = []
    processed_words = dict()
    counter = 1
    for word in words:
        if word not in processed_words:
            processed_words[word] = counter
            counter += 1
        result.append(processed_words[word])

    return result

if __name__ == "__main__":
    print(wordreplace("Hi hey hello hey hi hello"))

 

Desktop: Intel i9-10850K (R9 3900X died 😢 )| MSI Z490 Tomahawk | RTX 2080 (borrowed from work) - MSI GTX 1080 | 64GB 3600MHz CL16 memory | Corsair H100i (NF-F12 fans) | Samsung 970 EVO 512GB | Intel 665p 2TB | Samsung 830 256GB| 3TB HDD | Corsair 450D | Corsair RM550x | MG279Q

Laptop: Surface Pro 7 (i5, 16GB RAM, 256GB SSD)

Console: PlayStation 4 Pro

Link to comment
Share on other sites

Link to post
Share on other sites

Here is my solution

 

def wordreplace(aString):
	print(aString)
	str = aString.lower()
	str = str.split()
	a = {}
	b = []
	for s in str:
		a[s] = 0
	for i in range(0,len(str)):
		if a[str[i]] == 0:
			a[str[i]] = i+1
		b.append(a[str[i]])
	return b		
	
print(wordreplace('Hi hey hello hey hi hello'))

Output:

Hi hey hello hey hi hello
[1, 2, 3, 2, 1, 3]

The first loop is slightly inefficient as it will overwrite items already in the dictionary. Works though xD

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Or if you really wanted to have fun you could do the first step of a Huffman tree and number them based on frequency...although long run that works best at the individual character level, not the words.

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, vorticalbox said:

Here is my solution

 


def wordreplace(aString):
	print(aString)
	str = aString.lower()
	str = str.split()
	a = {}
	b = []
	for s in str:
		a[s] = 0
	for i in range(0,len(str)):
		if a[str[i]] == 0:
			a[str[i]] = i+1
		b.append(a[str[i]])
	return b		
	
print(wordreplace('Hi hey hello hey hi hello'))

Output:


Hi hey hello hey hi hello
[1, 2, 3, 2, 1, 3]

The first loop is slightly inefficient as it will overwrite items already in the dictionary. Works though xD

Thank you for this! :)

Link to comment
Share on other sites

Link to post
Share on other sites

2 hours ago, mathijs727 said:

If i got it correctly this should do what you want:


def wordreplace(text):
    words = text.lower().split(' ')

    result = []
    processed_words = dict()
    counter = 1
    for word in words:
        if word not in processed_words:
            processed_words[word] = counter
            counter += 1
        result.append(processed_words[word])

    return result

if __name__ == "__main__":
    print(wordreplace("Hi hey hello hey hi hello"))

 

Ah ok, thanks for the reply! Would you mind explaining the below:

if __name__ == "__main__":

as I am new to python, sort of! (1 year of learning so far)

 

Thanks again! :)

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, CandleJakk said:

Ah ok, thanks for the reply! Would you mind explaining the below:


if __name__ == "__main__":

as I am new to python, sort of! (1 year of learning so far)

 

Thanks again! :)

 

http://stackoverflow.com/questions/419163/what-does-if-name-main-do

 

Quote

When the Python interpreter reads a source file, it executes all of the code found in it.

Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.

In the case of your script, let's assume that it's executing as the main function, e.g. you said something like


python threading_example.py

on the command line. After setting up the special variables, it will execute the import statement and load those modules. It will then evaluate the def block, creating a function object and creating a variable called myfunction that points to the function object. It will then read the if statement and see that __name__ does equal "__main__", so it will execute the block shown there.

One of the reasons for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.

 

 

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, CandleJakk said:

Don't have the time to read this right now, but I'll be sure to read this later this evening. Thanks a lot for your help! :)

I put the main part in a quote for you, though there is an extra link in the source that i didn't include.

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×