Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
To be more specific I'd like to figure out how to:
name.replace xX with y if x exists, if not then just replace X
I've searched this forum for an hour now, make it two, and all I find is how to replace one thing with another, which by now is pretty easy.
/a
you can just run:
output = name.replace('xX','y').replace('X','y')
Example:
name = "123xX345X"
output = "123y345y"
Sounds like a job for regular expression x?X:
>>> import re
>>> text = " test xX blabla"
>>> re.sub('x?X', 'y', text)
' test y blabla'
>>> text = " test X blabla"
>>> re.sub('x?X', 'y', text)
' test y blabla'
Quote from docs about ? mark:
The question mark character, ?, matches either once or zero times; you
can think of it as marking something as being optional. For example,
home-?brew matches either homebrew or home-brew.
if 'x' in name:
name = name.replace('xX','y')
else:
name = name.replace('X','y')
From your example above this is a slightly more involved problem. You have to make sure to do your renames in the root namespace or things can get nasty. You also run the risk of renaming parents before children, which will make it hard to get at the children with one call to ls. So:
def replace_with_any_namespace(src, tgt):
cmds.namespace(set=":")
results = {}
xforms = cmds.ls(r=True, tr=True, l=True) # use long paths and recursive to get all namespaces
xforms = [i for i in xforms if src in i] # only work on items with your target pattern
xforms.sort()
xforms.reverse() # sort and reverse means children get renamed before parents
for item in xforms:
path, sep, shortname = item.rpartition("|") # gets only the last name
newname = shortname.replace(src, tgt) # this should be fine even if the namespace is there
results[item] = cmds.ls(cmds.rename ( item, newname), l=True)[0]
# the paths and returns are all long paths so there are no ambiguities
return results
Are you trying to move things out of their namespaces with this? Thats easier:
cmds.namespace(mv = ("R", ":"), force=True)
which moves everything in R:* to the base namespace. This will probably result in some renames, however. You might want to put important nodes into a set before you call this so you can find them.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have a simple code to get user email information, I got a problem about something :
import sys
try:
argx = sys.argv(1)
except:
print("Please Input an email.")
Example For User argument :
py main.py example#example.com
I want to take arg (input) after the # char and the . char.
I need this to check the email provider, domain name and other stuff about the email.
Example of the thing i want :
import sys
try:
argx = sys.argv(1)
x = "The argument after the char #, and the ."
except:
print("Please Input an email.")
if(x.lower() == "gmail") :
gmail()
elif(x.lower == "protonmail") :
protonmail()
You can use split function of a string in order to split a string
like
x = 'name#example.com' #Your input
email = x.split('#') # will give ['name','example.com']
provider = email[1].split('.')[0] # will give 'example'
Asuming you have the following email example#example.com. In python you can split a string with the split function. The function itself needs a delimeter. In your case the delimeter would be #. The return value of the split function is an array.
parts_of_mail = email.split("#")
>>> [example, example.com]
You now have the array parts_of_mail, which stores the left and right part of the email. You can now split the string again, like above:
provider_info = parts_of_mail[1].split(".")
>>> [example, com]
Finally you can check the provider information:
if provider_info[0].lower() == "example":
# do stuff here
elif provider_info[0].lower() == "gmail":
# do stuff here
Note: provider_info[0] stores the provider and provider_info[1] stores the domain.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm taking an intro programming class and am working ahead on some assignments that aren't due for a few weeks. This one asks me to take three text files - names, titles, and descriptions - and use them to randomly generate "fantasy character" names. My code runs and does what I want it to, but I feel like it's cluttered and could be cleaned up quite a bit. Keep in mind that this is an INTRO course and in class have just covered basic boolean logic, loops, arrays, etc.; not classes, object-oriented, or any advanced stuff (I'm trying to learn some of this on my own).
import random
def main():
for i in range(10):
# Load names, titles, descriptions into arrays
names = loadFile('names.txt')
title = loadFile('titles.txt')
descriptor = loadFile('descriptors.txt')
# Generate random number based on list length
nameListLength = len(names)
titleListLength = len(title)
descListLength = len(descriptor)
firstNameIndex = random.randrange(nameListLength)
lastNameIndex = random.randrange(nameListLength)
randTitleIndex = random.randrange(titleListLength)
randDescriptor = random.randrange(descListLength)
# Choose random list entry
firstName = names[firstNameIndex]
lastName = names[lastNameIndex]
title2 = title[randTitleIndex]
description = descriptor[randDescriptor]
nameList = [title2, firstName, lastName, description]
dumpFile(nameList)
print(title2, firstName, lastName, 'the', description)
print()
print('These names have been written to \"CharacterNames.txt\".')
def dumpFile(nameList):
title = str(nameList[0])
firstName = str(nameList[1])
lastName = str(nameList[2])
descriptor = str(nameList[3])
outfile = open('CharacterNames.txt', 'a')
outfile.write(title + ' ' + firstName + ' ' + lastName + ' ' +
'the' + ' ' + descriptor + '\n')
outfile.write('\n')
outfile.close()
def loadFile(nameFile):
nameList = open(nameFile, 'r')
nameArray = []
for line in nameList:
name = line
name = name.rstrip('\n')
nameArray.append(name)
nameList.close()
return nameArray
main()
I see value in having others look at your code and rewrite it as they would do it. I kind of ignored your restriction on "any advanced stuff," although I don't think any of it will be too complicated for you to intuit. Here's my rewrite:
import random
def generatePerson(names=loadFile('names.txt'),
titles=loadFile('titles.txt'),
descriptons=loadFile('descriptors.txt')):
firstName = random.choice(names)
lastName = random.choice(names)
title = random.choice(titles)
description = random.choice(descriptons)
return '{} {} {} the {}'.format(title, firstName, lastName, description)
def main():
people = [generatePerson() for _ in range(10)]
dumpFile('\n\n'.join(people))
print('\n'.join(people))
print('\nThese names have been written to "CharacterNames.txt".')
def dumpFile(data, filename='CharacterNames.txt'):
with open(filename, 'a') as outfile:
outfile.write(data)
def loadFile(nameFile):
with open(nameFile, 'r') as nameList:
return nameList.read().splitlines()
if __name__ == '__main__':
main()
It still resembles your code in many ways, however, most of it has been rewritten. Now for details on some of the more drastic changes.
I moved the code related to picking random strings from the three lists into its own function generatePerson. This makes the easier to maintain in case the method of generating a random person or something else changes in the future.
I greatly simplified the logic of picking the random strings by using random.choice.
I used a trick that uses default arguments in generatePerson to avoid reading from the three files each time a random name is created. The only part of this trick that you should know for now is that the values of default arguments are created only once in Python.
Instead of passing a list into dumpFile, I opted to pass a string, which I can then immediately write to the file. This makes more sense because I had generatePerson return the formatted string for that person rather than [title, firstName, lastName, description].
This is mostly just my preference, but I don't really like for-loops, so in main I used a list comprehension to create a list of 10 random names. From there, I used str.join to create a single string with all ten names that is suitable to be passed to dumpFile and print.
I believe that is (nearly) all of the changes I made. If I missed something or if you need further clarification on anything I mentioned either comment on my answer or just ask a new question.
Move file operations before the 'for' loop - there is no need to re-read the files 10 times. That should make the application run much faster.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to add 18 list items to a 3 text file, 6 items for each them. paths[0] and paths[1] text files are correct but third one paths[2] only gets 3 items.
mainStudents = ["1 Name Surname D1", "2 Name Surname D2" ...16x]
def randomize(path):
count = 0
currentpathIs = getprojdir + "\\" + "\shuffled" + path
print(currentpathIs)
with open(currentpathIs, "a+") as file:
while True:
try:
file.write(mainStudents[count] + "\n")
del(mainStudents[count])
print(count)
count += 1
except Exception as e:
print(mainStudents)
break
if count == 6:
break
randomize(paths[0])
randomize(paths[1])
randomize(paths[2])
I'm getting this error:
Traceback (most recent call last):
File "C:\Users\user\Desktop\New folder\python.py", line 53, in randomize(paths[2])
File "C:\Users\user\Desktop\New folder\python.py", line 43, in randomize
file.write(mainStudents[count] + "\n")
IndexError: list index out of range
But there's 3 items left in mainStudents list?
The problem you have is that when you delete the item from your list, you are then decreasing its size. Therefore, your count is going to increment and then try to access an index that no longer exists. Take a very simple example of just having a list of size two:
mainStudents = ["1 Name Surname D1", "2 Name Surname D2"]
Now, when you call your method, what is going to happen, the first iteration will work, because you will access mainStudents[0].
But, on your second iteration, you have deleted that item from the list, so now your list looks like:
['2 Name Surname D2']
Which is now a list of size one, and the index access for it would be 0.
So, the next iteration of your while loop will have count at 1. Therefore, that is exactly where your IndexError is coming from.
The combination of deciding to use a while loop and del items from your list is what is causing issues. Instead, choose what it is exactly you want to iterate over, which from your logic seems like it is mainStudents. So why not just do that instead?
def randomize(path):
currentpathIs = getprojdir + "\\" + "\shuffled" + path
print(currentpathIs)
with open(currentpathIs, "a+") as file:
for student in mainStudents:
file.write(student + "\n")
And you can further simplify that by simply taking your list and converting it to a string separated by \n by using the available string method, join:
'\n'.join(mainStudents)
Furthermore, there are available methods to facilitate path creation. Take a look at the os module. More specifically os.path.join. So, your code can be further simplified to:
from os.path import join
def randomize(path):
currentpathIs = join(getprojdir, shuffled, path)
with open(currentpathIs, "a+") as file:
file.write('\n'.join(mainStudents))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Help guys!!!
List of 150 text files,
One text file with query texts: (
SRR1005851
SRR1299210
SRR1021605
SRR1299782
SRR1299369
SRR1006158
...etc).
I want to search for each of this query texts from the list of 150 text files.
if for example SRR1005851 is found in at least 120 of the files, SRR1005851 will be appended in an output file.
the search will iterate all search query text and through all 150 files.
Summary: I am looking for which query text is found in at least 90% of the 150 files.
I don't think I fully understand your question. Posting your code and an example file would have been very helpful.
This code will count all entries in all files, then it will identify unique entries per file. After that, it will count each entry's occurrence in each file. Then, it will select only entries that appeared at least in 90% of all files.
Also, this code could have been shorter, but for readability's sake, I created many variables, with long, meaningful names.
Please read the comments ;)
import os
from collections import Counter
from sys import argv
# adjust your cut point
PERCENT_CUT = 0.9
# here we are going to save each file's entries, so we can sum them later
files_dict = {}
# total files seems to be the number you'll need to check against count
total_files = 0;
# raw total entries, even duplicates
total_entries = 0;
unique_entries = 0;
# first argument is script name, so have the second one be the folder to search
search_dir = argv[1]
# list everything under search dir - ideally only your input files
# CHECK HOW TO READ ONLY SPECIFIC FILE types if you have something inside the same folder
files_list = os.listdir(search_dir)
total_files = len(files_list)
print('Files READ:')
# iterate over each file found at given folder
for file_name in files_list:
print(" "+file_name)
file_object = open(search_dir+file_name, 'r')
# returns a list of entries with 'newline' stripped
file_entries = map(lambda it: it.strip("\r\n"), file_object.readlines())
# gotta count'em all
total_entries += len(file_entries)
# set doesn't allow duplicate entries
entries_set = set(file_entries)
#creates a dict from the set, set each key's value to 1.
file_entries_dict = dict.fromkeys(entries_set, 1)
# entries dict is now used differenty, each key will hold a COUNTER
files_dict[file_name] = Counter(file_entries_dict)
file_object.close();
print("\n\nALL ENTRIES COUNT: "+str(total_entries))
# now we create a dict that will hold each unique key's count so we can sum all dicts read from files
entries_dict = Counter({})
for file_dict_key, file_dict_value in files_dict.items():
print(str(file_dict_key)+" - "+str(file_dict_value))
entries_dict += file_dict_value
print("\nUNIQUE ENTRIES COUNT: "+str(len(entries_dict.keys())))
# print(entries_dict)
# 90% from your question
cut_line = total_files * PERCENT_CUT
print("\nNeeds at least "+str(int(cut_line))+" entries to be listed below")
#output dict is the final dict, where we put entries that were present in > 90% of the files.
output_dict = {}
# this is PYTHON 3 - CHECK YOUR VERSION as older versions might use iteritems() instead of items() in the line belows
for entry, count in entries_dict.items():
if count > cut_line:
output_dict[entry] = count;
print(output_dict)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
The code below reads lines from a file, then it executes the custom function (My_Function) and return values to the variables(e.g. condition_A)
for line in input_file:
if condition_A:
condition_A = My_Function(A_tuple[0], B_tuple[0])
if condition_B:
condition_B = My_Function(A_tuple[1], B_tuple[1])
if condition_C:
condition_C = My_Function(A_tuple[2], B_tuple[2])
if condition_D:
condition_D = My_Function(A_tuple[3], B_tuple[3])
if condition_E:
condition_E = My_Function(A_tuple[4], B_tuple[4])
...
My question is: can the code be modified to more elegant version? After all, many code is similar(I don't want to define another function to simplify it because the code is still similar after the new function is defined). thanks.
Instead of having 5 variables condition_*, use a list, conditions:
conditions=[1]*5 # initialize conditions as you wish
for line in input_file:
for i,condition in enumerate(conditions):
if condition:
conditions[i]=My_Function(A_tuple[i],B_tuple[i])
What about something like
conditions = [condition_A, condition_B, condition_C, condition_D, condition_E]
condition_test = lambda c, i: My_Function(A_tuple[i], B_tuple[i]) if c else c
for line in input_file:
conditions = [condition_test(c, i) for i, c in enumerate(conditions)]
'line' is not referenced in teh loop, is that an error in simplifying it for posting?
How about
condition=1 #or 2 or...
for line in input_file:
My_Function(A_tuple[condition],B_tuple[condition])
Before refactoring your code on a purely syntactic level (which is covered in examples above), it might be useful to evaluate what you're doing with the code on a functional level
Check out your condition_x variables. I think you might be using the same variable for two different things (both type-wise and logically) - usually a bad idea in a weakly typed language. It looks to me as if the user sets a condition to true or false, and then that condition is assigned the output - is the output boolean? is it related to the original value of that variable? Rethinking this might lead to more understandable code.
It is also difficult to evaluate how this can be refactored without seeing what goes in to condition_x - since these might have commonalities.
One more sample(not solution) based on unutbu's:
data = [1,2,3,'',4,5,6, '', 0]
for i in (i for i in xrange(len(data)) if data[i] not in ['',0]):
data[i] += 1
Sorry if duplicate
Here is a generic solution where you can have custom index and you can also access conditions by name if need be and it can be easily extended to add any new complexities
class Condition(object):
def __init__(self, active, index1, index2):
self.active = active
self.index1 = index1
self.index2 = index2
conditions = {
'A': Condition(True,0,0),
'B': Condition(True,1,1),
'C': Condition(True,2,2),
'D': Condition(True,3,3),
'E': Condition(True,4,4),
}
for line in input_file:
for condition in conditions.itervalues():
if condition.active:
condition.active = My_Function(A_tuple[condition.active.index1], B_tuple[condition.active.index2])