Best Python code snippet using pyatom_python
format.py
Source:format.py
1import re2from dragonfly import (3 Clipboard,4 Pause,5)6from lib.dynamic_aenea import (7 Key,8 Text,9)10letterMap = {11 "A\\letter": "alpha",12 "B\\letter": "bravo",13 "C\\letter": "charlie",14 "D\\letter": "delta",15 "E\\letter": "echo",16 "F\\letter": "foxtrot",17 "G\\letter": "golf",18 "H\\letter": "hotel",19 "I\\letter": "india",20 "J\\letter": "juliet",21 "K\\letter": "kilo",22 "L\\letter": "lima",23 "M\\letter": "mike",24 "N\\letter": "november",25 "O\\letter": "oscar",26 "P\\letter": "papa",27 "Q\\letter": "quebec",28 "R\\letter": "romeo",29 "S\\letter": "sierra",30 "T\\letter": "tango",31 "U\\letter": "uniform",32 "V\\letter": "victor",33 "W\\letter": "whiskey",34 "X\\letter": "x-ray",35 "Y\\letter": "yankee",36 "Z\\letter": "zulu",37}38class FormatTypes:39 camelCase = 140 pascalCase = 241 snakeCase = 342 squash = 443 upperCase = 544 lowerCase = 645 dashify = 746 dotify = 847 spokenForm = 948def strip_dragon_info(text):49 newWords = []50 words = str(text).split(" ")51 for word in words:52 if word.startswith("\\backslash"):53 word = "\\" # Backslash requires special handling.54 elif word.find("\\") > -1:55 word = word[:word.find("\\")] # Remove spoken form info.56 newWords.append(word)57 return newWords58def extract_dragon_info(text):59 newWords = []60 words = str(text).split(" ")61 for word in words:62 if word in letterMap.keys():63 word = letterMap[word]64 elif word.rfind("\\") > -1:65 pos = word.rfind("\\") + 166 if (len(word) - 1) >= pos:67 word = word[pos:] # Remove written form info.68 else:69 word = ""70 newWords.append(word)71 return newWords72def format_camel_case(text):73 newText = ""74 words = strip_dragon_info(text)75 for word in words:76 if newText == '':77 newText = word[:1].lower() + word[1:]78 else:79 newText = '%s%s' % (newText, word.capitalize())80 return newText81def format_pascal_case(text):82 newText = ""83 words = strip_dragon_info(text)84 for word in words:85 newText = '%s%s' % (newText, word.capitalize())86 return newText87def format_snake_case(text):88 newText = ""89 words = strip_dragon_info(text)90 for word in words:91 if newText != "" and newText[-1:].isalnum() and word[-1:].isalnum():92 word = "_" + word # Adds underscores between normal words.93 newText += word.lower()94 return newText95def format_dashify(text):96 newText = ""97 words = strip_dragon_info(text)98 for word in words:99 if newText != "" and newText[-1:].isalnum() and word[-1:].isalnum():100 word = "-" + word # Adds dashes between normal words.101 newText += word102 return newText103def format_dotify(text):104 newText = ""105 words = strip_dragon_info(text)106 for word in words:107 if newText != "" and newText[-1:].isalnum() and word[-1:].isalnum():108 word = "." + word # Adds dashes between normal words.109 newText += word110 return newText111def format_squash(text):112 newText = ""113 words = strip_dragon_info(text)114 for word in words:115 newText = '%s%s' % (newText, word)116 return newText117def format_upper_case(text):118 newText = ""119 words = strip_dragon_info(text)120 for word in words:121 if newText != "" and newText[-1:].isalnum() and word[-1:].isalnum():122 word = " " + word # Adds spacing between normal words.123 newText += word.upper()124 return newText125def format_lower_case(text):126 newText = ""127 words = strip_dragon_info(text)128 for word in words:129 if newText != "" and newText[-1:].isalnum() and word[-1:].isalnum():130 if newText[-1:] != "." and word[0:1] != ".":131 word = " " + word # Adds spacing between normal words.132 newText += word.lower()133 return newText134def format_spoken_form(text):135 newText = ""136 words = extract_dragon_info(text)137 for word in words:138 if newText != "":139 word = " " + word140 newText += word141 return newText142FORMAT_TYPES_MAP = {143 FormatTypes.camelCase: format_camel_case,144 FormatTypes.pascalCase: format_pascal_case,145 FormatTypes.snakeCase: format_snake_case,146 FormatTypes.squash: format_squash,147 FormatTypes.upperCase: format_upper_case,148 FormatTypes.lowerCase: format_lower_case,149 FormatTypes.dashify: format_dashify,150 FormatTypes.dotify: format_dotify,151 FormatTypes.spokenForm: format_spoken_form,152}153def format_text(text, formatType=None):154 if formatType:155 if type(formatType) != type([]):156 formatType = [formatType]157 result = ""158 method = None159 for value in formatType:160 if not result:161 if formatType == FormatTypes.spokenForm:162 result = text.words163 else:164 result = str(text)165 method = FORMAT_TYPES_MAP[value]166 result = method(result)167 Text("%(text)s").execute({"text": result})168def camel_case_text(text):169 """Formats dictated text to camel case.170 Example:171 "'camel case my new variable'" => "myNewVariable".172 """173 newText = format_camel_case(text)174 Text("%(text)s").execute({"text": newText})175def camel_case_count(n):176 """Formats n words to the left of the cursor to camel case.177 Note that word count differs between editors and programming languages.178 The examples are all from Eclipse/Python.179 Example:180 "'my new variable' *pause* 'camel case 3'" => "myNewVariable".181 """182 saveText = _get_clipboard_text()183 cutText = _select_and_cut_text(n)184 if cutText:185 endSpace = cutText.endswith(' ')186 text = _cleanup_text(cutText)187 newText = _camelify(text.split(' '))188 if endSpace:189 newText = newText + ' '190 newText = newText.replace("%", "%%") # Escape any format chars.191 Text(newText).execute()192 else: # Failed to get text from clipboard.193 Key('c-v').execute() # Restore cut out text.194 _set_clipboard_text(saveText)195def _camelify(words):196 """Takes a list of words and returns a string formatted to camel case.197 Example:198 ["my", "new", "variable"] => "myNewVariable".199 """200 newText = ''201 for word in words:202 if newText == '':203 newText = word[:1].lower() + word[1:]204 else:205 newText = '%s%s' % (newText, word.capitalize())206 return newText207def pascal_case_text(text):208 """Formats dictated text to pascal case.209 Example:210 "'pascal case my new variable'" => "MyNewVariable".211 """212 newText = format_pascal_case(text)213 Text("%(text)s").execute({"text": newText})214def pascal_case_count(n):215 """Formats n words to the left of the cursor to pascal case.216 Note that word count differs between editors and programming languages.217 The examples are all from Eclipse/Python.218 Example:219 "'my new variable' *pause* 'pascal case 3'" => "MyNewVariable".220 """221 saveText = _get_clipboard_text()222 cutText = _select_and_cut_text(n)223 if cutText:224 endSpace = cutText.endswith(' ')225 text = _cleanup_text(cutText)226 newText = text.title().replace(' ', '')227 if endSpace:228 newText = newText + ' '229 newText = newText.replace("%", "%%") # Escape any format chars.230 Text(newText).execute()231 else: # Failed to get text from clipboard.232 Key('c-v').execute() # Restore cut out text.233 _set_clipboard_text(saveText)234def snake_case_text(text):235 """Formats dictated text to snake case.236 Example:237 "'snake case my new variable'" => "my_new_variable".238 """239 newText = format_snake_case(text)240 Text("%(text)s").execute({"text": newText})241def snake_case_count(n):242 """Formats n words to the left of the cursor to snake case.243 Note that word count differs between editors and programming languages.244 The examples are all from Eclipse/Python.245 Example:246 "'my new variable' *pause* 'snake case 3'" => "my_new_variable".247 """248 saveText = _get_clipboard_text()249 cutText = _select_and_cut_text(n)250 if cutText:251 endSpace = cutText.endswith(' ')252 text = _cleanup_text(cutText.lower())253 newText = '_'.join(text.split(' '))254 if endSpace:255 newText = newText + ' '256 newText = newText.replace("%", "%%") # Escape any format chars.257 Text(newText).execute()258 else: # Failed to get text from clipboard.259 Key('c-v').execute() # Restore cut out text.260 _set_clipboard_text(saveText)261def squash_text(text):262 """Formats dictated text with whitespace removed.263 Example:264 "'squash my new variable'" => "mynewvariable".265 """266 newText = format_squash(text)267 Text("%(text)s").execute({"text": newText})268def squash_count(n):269 """Formats n words to the left of the cursor with whitespace removed.270 Excepting spaces immediately after comma, colon and percent chars.271 Note: Word count differs between editors and programming languages.272 The examples are all from Eclipse/Python.273 Example:274 "'my new variable' *pause* 'squash 3'" => "mynewvariable".275 "'my<tab>new variable' *pause* 'squash 3'" => "mynewvariable".276 "( foo = bar, fee = fye )", 'squash 9'" => "(foo=bar, fee=fye)"277 """278 saveText = _get_clipboard_text()279 cutText = _select_and_cut_text(n)280 if cutText:281 endSpace = cutText.endswith(' ')282 text = _cleanup_text(cutText)283 newText = ''.join(text.split(' '))284 if endSpace:285 newText = newText + ' '286 newText = _expand_after_special_chars(newText)287 newText = newText.replace("%", "%%") # Escape any format chars.288 Text(newText).execute()289 else: # Failed to get text from clipboard.290 Key('c-v').execute() # Restore cut out text.291 _set_clipboard_text(saveText)292def expand_count(n):293 """Formats n words to the left of the cursor by adding whitespace in294 certain positions.295 Note that word count differs between editors and programming languages.296 The examples are all from Eclipse/Python.297 Example, with to compact code:298 "result=(width1+width2)/2 'expand 9' " => "result = (width1 + width2) / 2"299 """300 saveText = _get_clipboard_text()301 cutText = _select_and_cut_text(n)302 if cutText:303 endSpace = cutText.endswith(' ')304 cutText = _expand_after_special_chars(cutText)305 reg = re.compile(306 r'([a-zA-Z0-9_\"\'\)][=\+\-\*/\%]|[=\+\-\*/\%][a-zA-Z0-9_\"\'\(])')307 hit = reg.search(cutText)308 count = 0309 while hit and count < 10:310 cutText = cutText[:hit.start() + 1] + ' ' + \311 cutText[hit.end() - 1:]312 hit = reg.search(cutText)313 count += 1314 newText = cutText315 if endSpace:316 newText = newText + ' '317 newText = newText.replace("%", "%%") # Escape any format chars.318 Text(newText).execute()319 else: # Failed to get text from clipboard.320 Key('c-v').execute() # Restore cut out text.321 _set_clipboard_text(saveText)322def _expand_after_special_chars(text):323 reg = re.compile(r'[:,%][a-zA-Z0-9_\"\']')324 hit = reg.search(text)325 count = 0326 while hit and count < 10:327 text = text[:hit.start() + 1] + ' ' + text[hit.end() - 1:]328 hit = reg.search(text)329 count += 1330 return text331def uppercase_text(text):332 """Formats dictated text to upper case.333 Example:334 "'upper case my new variable'" => "MY NEW VARIABLE".335 """336 newText = format_upper_case(text)337 Text("%(text)s").execute({"text": newText})338def uppercase_count(n):339 """Formats n words to the left of the cursor to upper case.340 Note that word count differs between editors and programming languages.341 The examples are all from Eclipse/Python.342 Example:343 "'my new variable' *pause* 'upper case 3'" => "MY NEW VARIABLE".344 """345 saveText = _get_clipboard_text()346 cutText = _select_and_cut_text(n)347 if cutText:348 newText = cutText.upper()349 newText = newText.replace("%", "%%") # Escape any format chars.350 Text(newText).execute()351 else: # Failed to get text from clipboard.352 Key('c-v').execute() # Restore cut out text.353 _set_clipboard_text(saveText)354def lowercase_text(text):355 """Formats dictated text to lower case.356 Example:357 "'lower case John Johnson'" => "john johnson".358 """359 newText = format_lower_case(text)360 Text("%(text)s").execute({"text": newText})361def lowercase_count(n):362 """Formats n words to the left of the cursor to lower case.363 Note that word count differs between editors and programming languages.364 The examples are all from Eclipse/Python.365 Example:366 "'John Johnson' *pause* 'lower case 2'" => "john johnson".367 """368 saveText = _get_clipboard_text()369 cutText = _select_and_cut_text(n)370 if cutText:371 newText = cutText.lower()372 newText = newText.replace("%", "%%") # Escape any format chars.373 Text(newText).execute()374 else: # Failed to get text from clipboard.375 Key('c-v').execute() # Restore cut out text.376 _set_clipboard_text(saveText)377def _cleanup_text(text):378 """Cleans up the text before formatting to camel, pascal or snake case.379 Removes dashes, underscores, single quotes (apostrophes) and replaces380 them with a space character. Multiple spaces, tabs or new line characters381 are collapsed to one space character.382 Returns the result as a string.383 """384 prefixChars = ""385 suffixChars = ""386 if text.startswith("-"):387 prefixChars += "-"388 if text.startswith("_"):389 prefixChars += "_"390 if text.endswith("-"):391 suffixChars += "-"392 if text.endswith("_"):393 suffixChars += "_"394 text = text.strip()395 text = text.replace('-', ' ')396 text = text.replace('_', ' ')397 text = text.replace("'", ' ')398 text = re.sub('[ \t\r\n]+', ' ', text) # Any whitespaces to one space.399 text = prefixChars + text + suffixChars400 return text401def _get_clipboard_text():402 """Returns the text contents of the system clip board."""403 clipboard = Clipboard()404 return clipboard.get_system_text()405def _select_and_cut_text(wordCount):406 """Selects wordCount number of words to the left of the cursor and cuts407 them out of the text. Returns the text from the system clip board.408 """409 clipboard = Clipboard()410 clipboard.set_system_text('')411 Key('cs-left/3:%s/10, c-x/10' % wordCount).execute()412 return clipboard.get_system_text()413def _set_clipboard_text(text):414 """Sets the system clip board content."""415 clipboard = Clipboard()416 clipboard.set_text(text) # Restore previous clipboard text....
mydataset.py
Source:mydataset.py
1# coding=utf-82import csv,codecs3from tgrocery import Grocery4import preprocessing as pp5import jieba6def getTrainTextList(cutModel=False):7 rawFileName='../data/rawtrain.txt'8 trainFileName='../data/train.txt'9 validateFileName='../data/validate.txt'10 #pp.splitfile(rawFileName,trainFileName,validateFileName)11 str=''12 trainlist=[]13 # train #################################14 filein=codecs.open(trainFileName,'r','utf-8')15 in_reader=filein.readlines()16 i=017 for line in in_reader:18 content=pp.getcontent(in_reader,i)19 i=i+120 if(i%5000==0):21 print ("%d "%(i))+'#'*3022 #if(i>10):23 #break24 if(content==''):25 print line26 else:27 str=content.split('\t')28 len=str[0].__len__()29 cuttext=jieba.cut(content[len+3:].strip(),cut_all=cutModel)30 jointext=' '.join(cuttext)31 trainstr=(str[1],jointext)32 trainlist.append(trainstr)33 filein.close()34 return trainlist35def getValidateTextList(cutModel=False):36 rawFileName='../data/rawtrain.txt'37 trainFileName='../data/train.txt'38 validateFileName='../data/validate.txt'39 #pp.splitfile(rawFileName,trainFileName,validateFileName)40 str=''41 trainlist=[]42 # train #################################43 filein=codecs.open(validateFileName,'r','utf-8')44 in_reader=filein.readlines()45 i=046 for line in in_reader:47 content=pp.getcontent(in_reader,i)48 i=i+149 if(i%5000==0):50 print ("%d "%(i))+'#'*3051 #if(i>10):52 #break53 if(content==''):54 print line55 else:56 str=content.split('\t')57 len=str[0].__len__()58 cuttext=jieba.cut(content[len+3:].strip(),cut_all=cutModel)59 jointext=' '.join(cuttext)60 trainstr=(str[1],jointext)61 trainlist.append(trainstr)62 filein.close()63 return trainlist64def getAllTrainTextList(cutModel=False):65 rawFileName='../data/rawtrain.txt'66 trainFileName='../data/train.txt'67 validateFileName='../data/validate.txt'68 #pp.splitfile(rawFileName,trainFileName,validateFileName)69 str=''70 trainlist=[]71 # train #################################72 filein=codecs.open(rawFileName,'r','utf-8')73 in_reader=filein.readlines()74 i=075 for line in in_reader:76 content=pp.getcontent(in_reader,i)77 i=i+178 if(i%5000==0):79 print ("%d "%(i))+'#'*3080 #if(i>10):81 #break82 if(content==''):83 print line84 else:85 str=content.split('\t')86 len=str[0].__len__()87 cuttext=jieba.cut(content[len+3:].strip(),cut_all=cutModel)88 jointext=' '.join(cuttext)89 trainstr=(str[1],jointext)90 trainlist.append(trainstr)91 filein.close()92 return trainlist93def getTestTextList(cutModel=False):94 testFileName='../data/test.txt'95 filetest=codecs.open(testFileName,'r','utf-8')96 test_reader=filetest.readlines()97 testTextList=[]98 i=099 for line in test_reader:100 content=pp.getcontent(test_reader,i)101 i=i+1102 #if(i>10):103 #break104 if(i%5000==0):105 print ("%d "%(i))+'#'*30106 if(content==''):107 print "test.py#"*3+line108 else:109 str=content.split('\t')110 len=str[0].__len__()111 #result=pipeline.predict(content[len+1:])112 cuttext=jieba.cut(content[len+1:].strip(),cut_all=cutModel)113 jointext=' '.join(cuttext)114 testTextList.append(jointext)115 filetest.close()116 return testTextList117def train():118 print 'train start '+'.'*30119 #grocery=Grocery('sample')120 grocery=Grocery('version1.0')121 grocery.train(trainlist)122 grocery.save()123 print 'train end '+'.'*30124if __name__ == '__main__' :...
train.py
Source:train.py
1# coding=utf-82import csv,codecs3from tgrocery import Grocery4import preprocessing as pp5import jieba6def getTrainTextList():7 rawFileName='../data/rawtrain.txt'8 trainFileName='../data/train.txt'9 validateFileName='../data/validate.txt'10 #pp.splitfile(rawFileName,trainFileName,validateFileName)11 str=''12 trainlist=[]13 # train #################################14 filein=codecs.open(trainFileName,'r','utf-8')15 in_reader=filein.readlines()16 i=017 for line in in_reader:18 content=pp.getcontent(in_reader,i)19 i=i+120 if(i%5000==0):21 print ("%d "%(i))+'#'*3022 #if(i>10):23 #break24 if(content==''):25 print line26 else:27 str=content.split('\t')28 len=str[0].__len__()29 cuttext=jieba.cut(content[len+3:])30 jointext=' '.join(cuttext)31 trainstr=(str[1],jointext)32 trainlist.append(trainstr)33 filein.close()34 return trainlist35def getValidateTextList():36 rawFileName='../data/rawtrain.txt'37 trainFileName='../data/train.txt'38 validateFileName='../data/validate.txt'39 #pp.splitfile(rawFileName,trainFileName,validateFileName)40 str=''41 trainlist=[]42 # train #################################43 filein=codecs.open(validateFileName,'r','utf-8')44 in_reader=filein.readlines()45 i=046 for line in in_reader:47 content=pp.getcontent(in_reader,i)48 i=i+149 if(i%5000==0):50 print ("%d "%(i))+'#'*3051 #if(i>10):52 #break53 if(content==''):54 print line55 else:56 str=content.split('\t')57 len=str[0].__len__()58 cuttext=jieba.cut(content[len+3:])59 jointext=' '.join(cuttext)60 trainstr=(str[1],jointext)61 trainlist.append(trainstr)62 filein.close()63 return trainlist64def getAllTrainTextList():65 rawFileName='../data/rawtrain.txt'66 trainFileName='../data/train.txt'67 validateFileName='../data/validate.txt'68 #pp.splitfile(rawFileName,trainFileName,validateFileName)69 str=''70 trainlist=[]71 # train #################################72 filein=codecs.open(rawFileName,'r','utf-8')73 in_reader=filein.readlines()74 i=075 for line in in_reader:76 content=pp.getcontent(in_reader,i)77 i=i+178 if(i%5000==0):79 print ("%d "%(i))+'#'*3080 #if(i>10):81 #break82 if(content==''):83 print line84 else:85 str=content.split('\t')86 len=str[0].__len__()87 cuttext=jieba.cut(content[len+3:])88 jointext=' '.join(cuttext)89 trainstr=(str[1],jointext)90 trainlist.append(trainstr)91 filein.close()92 return trainlist93def train():94 print 'train start '+'.'*3095 #grocery=Grocery('sample')96 grocery=Grocery('version1.0')97 grocery.train(trainlist)98 grocery.save()99 print 'train end '+'.'*30100if __name__ == '__main__' :...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!