Advertisement
furas

Python - example [FB:learnpython.org]

Oct 8th, 2016
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | None | 0 0
  1. #
  2. # https://www.facebook.com/groups/learnpython.org/permalink/1213762838688331/
  3. #
  4.  
  5. import tkinter as tk
  6. import re
  7.  
  8. # --- constants ---
  9.     # empty
  10. # --- classes ---
  11.     # empty
  12. # --- functions ---
  13.  
  14. def my_function():
  15.     # use entry_name.get() to get text
  16.  
  17.     save_file = open("AlanFile.txt","w")
  18.  
  19.     # ---
  20.    
  21.     word_list = re.split('\W+', text_entry.get(), flags=re.U)
  22.    
  23.     if word_list and word_list[0] == '':
  24.         word_list = word_list[1:]
  25.     if word_list and word_list[-1] == '':
  26.         word_list = word_list[:-1]
  27.    
  28.     for word in words_entry.get().split():
  29.         # I use `enumerate(..., 1) so I don't need `i+1` in other lines
  30.         indexes = [i for i, x in enumerate(word_list, 1) if x==word]
  31.  
  32.         result_text.insert('end', "%s: %s\n" % (word, indexes))
  33.         save_file.write("%s: %s\n" % (word, indexes))
  34.    
  35.     # ---
  36.  
  37.     words = []
  38.     for index in indexes_entry.get().split():
  39.         words.append(word_list[int(index)-1])
  40.    
  41.     text = " ".join(words)
  42.    
  43.     result_text.insert('end', text)
  44.     save_file.write(text)
  45.  
  46.     # ---
  47.  
  48.     result_text.insert('end', '\n-------\n')
  49.  
  50.     save_file.close()
  51.  
  52. # --- main ---
  53.    
  54. root = tk.Tk()
  55.  
  56. tk.Label(root, text="Enter text > ").grid(row=0, column=0, sticky='E')
  57. text_entry = tk.Entry(root)
  58. text_entry.grid(row=0, column=1, sticky='WE')
  59.  
  60. tk.Label(root, text="Enter words > ").grid(row=1, column=0, sticky='E')
  61. words_entry = tk.Entry(root)
  62. words_entry.grid(row=1, column=1, sticky='WE')
  63.  
  64. tk.Label(root, text="Enter indexes > ").grid(row=2, column=0, sticky='E')
  65. indexes_entry = tk.Entry(root)
  66. indexes_entry.grid(row=2, column=1, sticky='WE')
  67.  
  68. tk.Button(root, text="Run", command=my_function).grid(row=3, column=1)
  69.  
  70. result_text = tk.Text(root)
  71. result_text.grid(row=4, columnspan=2)
  72.  
  73. # I set some text for test
  74.  
  75. text_entry.insert(0, 'hello world of python')
  76. words_entry.insert(0, 'world python')
  77. indexes_entry.insert(0, '2 1')
  78.  
  79. # run program (start "the engine")
  80.  
  81. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement