Is there a way for Python to create paths with multiple sub-paths using shortcut syntax similar to this?
vars=project/{DEBIAN,usr/{bin,usr/{applications,icons,share}},computer}
Is there a way for Python to create paths with multiple sub-paths using shortcut syntax similar to this?
vars=project/{DEBIAN,usr/{bin,usr/{applications,icons,share}},computer}
Typically, my recommendation would have been to utilize a method similar to the following:
def combine(base, *others):
[base + o for o in others] if others else [base]
Following that, you could execute:
combine("task", "/folder", *combine("/users", *(combine("/files") + combine("/data", "/documents", "/archive", "/resources"))))
However, considering your preference for parsing a string, I have devised an alternative approach:
def split_by_comma(input_str):
starting_index = 0
current_level = 0
for index, char in enumerate(input_str):
if char == '{':
current_level += 1
elif char == '}':
current_level -= 1
elif char == ',' and current_level == 0:
yield input_str[starting_index:index]
starting_index = index + 1
yield input_str[starting_index:]
def split_string(input_str):
import re
pattern_found = False
for match in re.finditer("(\{.*\})",input_str):
pattern_found = True
for part in split_by_comma(input_str[match.start() + 1:match.end() - 1]):
for item in split_string(part):
yield input_str[:match.start()] + item + input_str[match.end():]
if not pattern_found:
yield input_str
cs_input = "x,y,z,{a,b,c},d"
print list(split_by_comma(cs_input)) # -> appears to be functioning correctly
input_val = "task/{FOLDER,user/{projects,usr/{static,folders,jobs}},machine}"
print input_val
for number, iteration in enumerate(split_string(input_val)): print number, iteration # -> working nicely.
Unfortunately, there is no built-in shorthand for this in Python. One way to achieve a similar result in a pythonic manner would be as follows:
vars = ["project" + path for path in (
["/DEBIAN"] +
["/usr" + path for path in (
['/bin'] +
['/usr' + path for path in [
"/applications",
"/icons",
"/share"]
]
)] +
['/computer']
)]
To simplify the process, you can create a function. Here's an alternative version using a lazy generator approach:
def expand(base, paths):
for path in paths:
if type(path) == str:
yield base + path
else:
for p in path:
yield base + p
vars = expand("project", [
"/debian",
expand("/usr", [
"/bin",
expand("/usr", [
"/applications",
"/icons",
"/share"
]),
"/computer"
])
])
Appreciate your response.
I prefer to write my code using unconventional lists like ["0,1,2,3,4,5,6,7,8,9".split(","),["a,b,c,d,e".split(",")]] for efficiency reasons.
Using this method eliminates the need for shift key presses and offers a more logical approach compared to traditional lists such as ["x","y","z"].
It would be beneficial to have a string operation in Python that mimics the bash syntax provided below...
Python syntax : project,[DEBIAN,usr,[bin,usr,[applications,icons,share/winpath]],computer]
Bash syntax : project/{DEBIAN,usr/{bin,usr/{applications,icons,share}},computer}
import re
def genpaths (multils, root=""):
suc=[]
for l in multils:
if type(l) == type([]):
suc.extend(genpaths (l, root+multils[multils.index(l)-1]+"/"))
else:
suc.append( root+l)
return filter(None, suc)
def easylist (s):
s=eval("['''"+re.sub("(\]+)(''',''')?", "'''\\1,'''",re.sub("(''',''')?(\[+)","''',\\2'''",re.sub(",","''','''",s)))+"''']")
return s
def bashlist (s):
s=eval("['''"+re.sub("(\}+)(''',''')?", "'''\\1,'''",re.sub("(/)?(\{+)","''',\\2'''",re.sub(",","''','''",s))).replace("{","[").replace("}","]")+"''']")
return s
def pythonGenPath (s):
return genpaths(bashlist (s))
def bashGenPath (s):
return genpaths(bashlist (s))
#testing
print pythonGenPath ("project,[DEBIAN,usr,[bin,usr,[applications,icons,share/winpath]],computer]")
print bashGenPath ("project/{DEBIAN,usr/{bin,usr/{applications,icons,share}},computer}")
The output shows :
['project', 'project/DEBIAN', 'project/usr', 'project/usr/bin', 'project/usr/usr', 'project/usr/usr/applications', 'project/usr/usr/icons', 'project/usr/usr/share', 'project/computer']
I have developed a program that determines the orientation of an image and straightens it if it is in any other orientation. This is achieved by rotating the image using its pred_val (implemented with Pytorch). I have structured the output as a dictionary, ...
Currently, I am facing a challenge with changing the foreground color of a button on my Mac running Big Sur. I have attempted to resolve this by installing tkmacosx, but it seems there may be an issue with the package. Whenever I run the code below or att ...
When working with a tuple items, I utilize the itertools library to generate the powerset: items = tuple(('a', 'b', 'c')) combos = powerset(items) def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) ( ...
Forgive me for the simplicity of my question, but I am looking to display: The total number and types of nodes with 0, 1, 2, or 3 children. The total number of nodes with 0, 1, 2, or 3 parents. Below is the simple script I have written. Thank you. Vicin ...
As a Matlab user transitioning into Python, I attempted to code a minimal version of the de2bi function in Python. This function converts a decimal number into binary with the right-most significant bit first. However, I encountered some confusion when wor ...
Assuming I have 2 dictionaries: d1={1:[2,3,str],2:[4,5,str2]} d2={3:[6,7],2:[8,9]} I am looking to generate a fresh dictionary which will include only the keys that are present in both dictionaries. new_d={2:[4,5,str2,8,9]} ...
Click here for JSON data on COVID-19 mobility trends. Here is a snippet of the JSON data: { "data": { "Albania": [ { "name": "driving", "title": "driving", "values": [ { "date": "2020-01-13", "value": "100" }, { "date": "2020-01-14", "value": "95.3" }, { ...
I am brand new to Python and encountering an issue that's frustrating me. Every time I attempt the command x, y, z = " ", I consistently get a ValueError message. The error I receive is as follows: ValueError: not enough values to unpack (expected 3, ...
Can someone help me extract a specific line from an HTML code using Python? For instance, in this website: The snippet of code is as follows: var episodes = [[8,54514],[7,54485],[6,54456],[5,54430],[4,54400],[3,54367],[2,54327],[1,54271]]; I am lookin ...
Is there a way to determine if a request is an ajax request in a controller method in Turbogears? Additionally, can a 'partial' be returned similar to Rails or Symfony when the request is an ajax request? I am aware of the json decorator, but I s ...
Trying to write news headlines into a CSV file using Python's CSV module has raised an issue regarding apostrophes. For instance, when there is an apostrophe in a headline like 'What’s So Great About Snapchat Anyway?', an encode error occu ...
Looking at the following list, I am in search of the lowest CPU value: [{'Device': 'A', 'CPU': 10.7, 'RAM': 32.5}, {'Device': 'B', 'CPU': 4.2, 'RAM': 32.4}, {'Device' ...
In an attempt to merge two distinct lists of lists based on shared elements, I find myself faced with a challenge. Consider the following: list1 = [['a1', 'a2', 'b2'], ['h1', 'h2'], ['c1', ' ...
I'm currently working on creating a YouTube Scraper. I have successfully extracted the desired data from the video, but I am facing an issue with scrolling to the end of the comments section. Below is the code snippet that I have used: from selenium ...
Looking for a solution to analyze the following: approved_countries = ['Germany', 'France'] We have 5 groups : {'Germany'} {'Germany', 'France'} {'Germany', 'France'} {'Germany&apo ...
Trying to deploy a static NextJS website involves exporting a distribution folder and uploading it to the server. An issue arises when clicking on a link to another path, such as '/about', which works fine. However, if the page is reloaded or th ...
Recently, I encountered an issue with my script that was designed for scraping images from Google using Selenium webdriver. The script is supposed to navigate through the images and fetch their URLs. However, during my last run of the script, it failed to ...
When it comes to overriding and inheritance, I've noticed that things are not working as expected in my code. Let me break down the scenario for you: I have three classes - Card, Treasure, and Copper. Copper inherits from Treasure, and Treasure inheri ...
I am looking to create a line and ribbon plot, similar to the ones generated with ggplot2 using geom_line + geom_ribbon. You can see an example of what I'm aiming for here: If possible, I would like to utilize the new seaborn.objects interface. Howev ...
Greetings, I am encountering a problem with the code snippet below. The specific issue is that after opening a submenu and attempting to send down arrow keys, it does not work properly unless I use a multiplier like *100. Any assistance on this matter wo ...