Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Defining a Function
#1
I have this code that sorts a document according to the words it contains. There is a pythonic way of counting the files classified as "_fruit" and "_veget" that I am moving to the folder untitled1

path_txt = 'temp'
files1 = os.listdir(path_txt)
for TXT in files1:
    with open(path_txt + '\\' + TXT, "r") as content: 
        key1 = False
        key2 = False
        search = re.search(r'\d{21,30}', content.read())        
        text = content.read()
        if ('apple' in text and 'banana' in text and 'orange') or \
                ('apple' in text and 'orange' in text and 'watermelon'):
            key1 = True
        elif ('pumpkin' in text or 'potato' in text) and \
                        'carrot' in text and '' in text and \
                        'beet' in text and not 'pineapple' in text and not 'orange' in text:
            key2 = True
    if search is not None:  
        name1 = search.group(0)         
        if key1:
            fp = os.path.join("untitled1", name1 + '_fruit' + "_%d.txt")
            postfix = 0
            while os.path.exists(fp % postfix):
                postfix += 1
        elif key2:
            fp = os.path.join("untitled1", name1 + '_veget' + "_%d.txt")
            postfix = 0
            while os.path.exists(fp % postfix):
                postfix += 1
        os.rename(
            os.path.join(path_txt, TXT),
            fp % postfix
        )
ps: I have 8 "for" loops in the same code doing similar things. I will apply for them as well.
Reply


Messages In This Thread
count booleans in an if - by mattt1998 - Dec-10-2017, 01:45 PM
RE: count booleans in an if - by Windspar - Dec-10-2017, 05:13 PM
Defining a Function - by mattt1998 - Dec-13-2017, 06:32 PM
RE: Defining a Function - by mpd - Dec-13-2017, 07:36 PM
RE: Defining a Function - by buran - Dec-14-2017, 07:02 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Conjugate Gradient having issues with defining A (function to solve [A]{x} = {b} ) DimosG 2 2,872 Sep-21-2021, 08:32 PM
Last Post: 1968Edwards
  Defining a function with input abcd 5 3,205 Feb-21-2021, 02:34 AM
Last Post: NullAdmin
  When Defining a Function with an Equation as a Default Argument, which Value Is Used? OJGeorge4 4 2,773 Apr-09-2020, 08:48 AM
Last Post: DeaD_EyE
  Problem with defining a function snow_y 4 3,273 Nov-26-2018, 02:13 AM
Last Post: snippsat
  IDLE indenting 29 columns after defining function Cosmo_Kane 1 2,458 Jun-03-2018, 08:53 AM
Last Post: Larz60+
  Defining an fsolve function to call later hegdep 1 3,129 Oct-25-2017, 07:38 AM
Last Post: hegdep
  init vs_init_ while defining method/function? hsunteik 1 3,689 Dec-24-2016, 08:27 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020