本文整理汇总了Python中music21.common.isIterable函数的典型用法代码示例。如果您正苦于以下问题:Python isIterable函数的具体用法?Python isIterable怎么用?Python isIterable使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了isIterable函数的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: names
def names(self, values):
if not common.isIterable(values):
raise exceptions21.MetadataException(
'.names must be a list -- do you mean .name instead?')
self._names = [] # reset
for n in values:
self._names.append(Text(n))
开发者ID:cuthbertLab,项目名称:music21,代码行数:7,代码来源:primitives.py
示例2: cacheMetadata
def cacheMetadata(corpusNames=('local',), verbose=True):
'''
Rebuild the metadata cache.
'''
if not common.isIterable(corpusNames):
corpusNames = [corpusNames]
for name in corpusNames:
corpora.Corpus._metadataBundles[name] = None
metadata.caching.cacheMetadata(corpusNames, verbose=verbose)
开发者ID:rondini,项目名称:music21,代码行数:9,代码来源:__init__.py
示例3: cacheMetadata
def cacheMetadata(corpusNames=('local',), verbose=True):
'''
Rebuild the metadata cache.
'''
if not common.isIterable(corpusNames):
corpusNames = [corpusNames]
for name in corpusNames:
# todo -- create cache names for local corpora
manager._metadataBundles[name] = None
metadata.caching.cacheMetadata(corpusNames, verbose=verbose)
开发者ID:chrisgreencorn,项目名称:music21,代码行数:10,代码来源:__init__.py
示例4: getWork
def getWork(workName,
movementNumber=None,
fileExtensions=None,
):
'''
this parse method is called from `corpus.parse()` and does nothing differently from it.
Searches all corpora for a file that matches the name and returns it parsed.
'''
addXMLWarning = False
workNameJoined = workName
mxlWorkName = workName
if workName in (None, ''):
raise CorpusException(
'a work name must be provided as an argument')
if not common.isListLike(fileExtensions):
fileExtensions = [fileExtensions]
if common.isIterable(workName):
workNameJoined = os.path.sep.join(workName)
if workNameJoined.endswith(".xml"):
# might be compressed MXL file
mxlWorkName = os.path.splitext(workNameJoined)[0] + ".mxl"
addXMLWarning = True
filePaths = None
for corpusObject in iterateCorpora():
workList = corpusObject.getWorkList(workName, movementNumber, fileExtensions)
if not workList and addXMLWarning:
workList = corpusObject.getWorkList(mxlWorkName, movementNumber, fileExtensions)
if not workList:
continue
if len(workList) >= 1:
filePaths = workList
break
if filePaths is None:
warningMessage = 'Could not find a'
if addXMLWarning:
warningMessage += 'n xml or mxl'
warningMessage += ' work that met this criterion: {0};'.format(workName)
warningMessage += ' if you are searching for a file on disk, '
warningMessage += 'use "converter" instead of "corpus".'
raise CorpusException(warningMessage)
else:
if len(filePaths) == 1:
return filePaths[0]
else:
return filePaths
开发者ID:fzalkow,项目名称:music21,代码行数:50,代码来源:manager.py
示例5: __init__
def __init__(self, pitches=None):
if pitches is None:
raise TranspositionException('Must have some input')
if not common.isIterable(pitches):
raise TranspositionException('Must be a list or tuple')
if not pitches:
raise TranspositionException(
'Must have at least one element in list')
# p0 = pitches[0]
# if not isinstance(p0, pitch.Pitch):
# raise TranspositionException('List must have pitch objects')
self.pitches = pitches
self.allTranspositions = None
self.allNormalOrders = None
self.distinctNormalOrders = None
开发者ID:ELVIS-Project,项目名称:music21,代码行数:15,代码来源:transposition.py
示例6: postProcessData
def postProcessData(self):
'''
Replace client.data with a list that only includes each key once.
'''
client = self.client
if client is None:
return []
from operator import itemgetter
countAxes = self.countAxes
if not common.isIterable(countAxes):
countAxes = (countAxes,)
axesIndices = tuple([self.axisDataMap[axisName] for axisName in countAxes])
thisIndex = self.axisDataMap[self.axisName]
selector = itemgetter(*axesIndices)
relevantData = [selector(innerTuple) for innerTuple in client.data]
# all the format dicts will soon be smooshed, so get all the data from it:
tupleFormatDict = {}
for dataPoint in client.data:
dataIndex = selector(dataPoint)
formatDict = dataPoint[-1]
if not isinstance(formatDict, dict):
continue
if dataIndex in tupleFormatDict: # already saw one:
tupleFormatDict[dataIndex].update(formatDict)
else:
tupleFormatDict[dataIndex] = formatDict
counter = collections.Counter(relevantData)
newClientData = []
for counterKey in counter:
innerList = [None] * (len(axesIndices) + 1)
if len(axesIndices) > 1:
for dependentIndex in axesIndices:
innerList[dependentIndex] = counterKey[dependentIndex]
else: # single axesIndices means the counterKey will not be a tuple:
innerList[axesIndices[0]] = counterKey
innerList[thisIndex] = counter[counterKey]
formatDict = tupleFormatDict.get(counterKey, {})
newClientData.append(tuple(innerList) + (formatDict,))
client.data = sorted(newClientData)
return client.data
开发者ID:cuthbertLab,项目名称:music21,代码行数:46,代码来源:axis.py
示例7: __init__
def __init__(self,
srcStream,
filterList=None,
restoreActiveSites=True,
activeInformation=None):
if srcStream.isSorted is False and srcStream.autoSort:
srcStream.sort()
self.srcStream = srcStream
self.index = 0
# use .elements instead of ._elements/etc. so that it is sorted...
self.srcStreamElements = srcStream.elements
self.streamLength = len(self.srcStreamElements)
# this information can help a
self.elementsLength = len(self.srcStream._elements)
self.sectionIndex = -1
self.iterSection = '_elements'
self.cleanupOnStop = False
self.restoreActiveSites = restoreActiveSites
self.overrideDerivation = None
if filterList is None:
filterList = []
elif not common.isIterable(filterList):
filterList = [filterList]
elif isinstance(filterList, tuple) or isinstance(filterList, set):
filterList = list(filterList) # mutable....
# self.filters is a list of expressions that
# return True or False for an element for
# whether it should be yielded.
self.filters = filterList
self._len = None
self._matchingElements = None
# keep track of where we are in the parse.
# esp important for recursive streams...
if activeInformation is not None:
self.activeInformation = activeInformation
else:
self.activeInformation = {}
self.updateActiveInformation()
开发者ID:fzalkow,项目名称:music21,代码行数:44,代码来源:iterator.py
示例8: cacheMetadata
def cacheMetadata(corpusNames=None,
useMultiprocessing=True,
verbose=False):
'''
Cache metadata from corpora in `corpusNames` as local cache files.
Call as ``metadata.cacheMetadata()``
'''
from music21.corpus import manager
localCorporaNames = manager.listLocalCorporaNames(skipNone=True)
if corpusNames is None:
corpusNames = localCorporaNames[:] + ['local', 'core',] # + 'virtual']
if not common.isIterable(corpusNames):
corpusNames = (corpusNames,)
timer = common.Timer()
timer.start()
# store list of file paths that caused an error
failingFilePaths = []
# the core cache is based on local files stored in music21
# (no-longer-existent virtual is on-line)
for corpusName in corpusNames:
corpusObject = manager.fromName(corpusName)
failingFilePaths += corpusObject.cacheMetadata(useMultiprocessing, verbose, timer)
message = 'cache: final writing time: {0} seconds'.format(timer)
if verbose is True:
environLocal.warn(message)
else:
environLocal.printDebug(message)
for failingFilePath in failingFilePaths:
message = 'path failed to parse: {0}'.format(failingFilePath)
if verbose is True:
environLocal.warn(message)
else:
environLocal.printDebug(message)
开发者ID:cuthbertLab,项目名称:music21,代码行数:43,代码来源:caching.py
示例9: makeRests
#.........这里部分代码省略.........
>>> a.makeRests(fillGaps = True, inPlace=True)
>>> a.show('text')
{0.0} <music21.stream.Measure 1 offset=0.0>
{0.0} <music21.clef.TrebleClef>
{0.0} <music21.meter.TimeSignature 4/4>
{0.0} <music21.note.Rest rest>
{4.0} <music21.stream.Measure 2 offset=4.0>
{0.0} <music21.note.Note C>
{5.0} <music21.note.Rest rest>
{8.0} <music21.stream.Measure 3 offset=8.0>
{0.0} <music21.note.Note D>
{1.0} <music21.bar.Barline style=final>
Obviously there are problems TODO: fix them
OMIT_FROM_DOCS
TODO: default inPlace = False
'''
from music21 import stream
if not inPlace: # make a copy
returnObj = copy.deepcopy(s)
else:
returnObj = s
#environLocal.printDebug([
# 'makeRests(): object lowestOffset, highestTime', oLow, oHigh])
if refStreamOrTimeRange is None: # use local
oLowTarget = 0
if timeRangeFromBarDuration and returnObj.isMeasure:
# NOTE: this will raise an exception if no meter can be found
oHighTarget = returnObj.barDuration.quarterLength
else:
oHighTarget = returnObj.highestTime
elif isinstance(refStreamOrTimeRange, stream.Stream):
oLowTarget = refStreamOrTimeRange.lowestOffset
oHighTarget = refStreamOrTimeRange.highestTime
#environLocal.printDebug([
# 'refStream used in makeRests', oLowTarget, oHighTarget,
# len(refStreamOrTimeRange)])
# treat as a list
elif common.isIterable(refStreamOrTimeRange):
oLowTarget = min(refStreamOrTimeRange)
oHighTarget = max(refStreamOrTimeRange)
#environLocal.printDebug([
# 'offsets used in makeRests', oLowTarget, oHighTarget,
# len(refStreamOrTimeRange)])
if returnObj.hasVoices():
bundle = returnObj.voices
else:
bundle = [returnObj]
for v in bundle:
v.elementsChanged() # required to get correct offset times
oLow = v.lowestOffset
oHigh = v.highestTime
# create rest from start to end
qLen = oLow - oLowTarget
if qLen > 0:
r = note.Rest()
r.duration.quarterLength = qLen
#environLocal.printDebug(['makeRests(): add rests', r, r.duration])
# place at oLowTarget to reach to oLow
v._insertCore(oLowTarget, r)
# create rest from end to highest
qLen = oHighTarget - oHigh
#environLocal.printDebug(['v', v, oHigh, oHighTarget, 'qLen', qLen])
if qLen > 0:
r = note.Rest()
r.duration.quarterLength = qLen
# place at oHigh to reach to oHighTarget
v._insertCore(oHigh, r)
v.elementsChanged() # must update otherwise might add double r
if fillGaps:
gapStream = v.findGaps()
if gapStream is not None:
for e in gapStream:
r = note.Rest()
r.duration.quarterLength = e.duration.quarterLength
v._insertCore(e.offset, r)
v.elementsChanged()
#environLocal.printDebug(['post makeRests show()', v])
# NOTE: this sorting has been found to be necessary, as otherwise
# the resulting Stream is not sorted and does not get sorted in
# preparing musicxml output
if v.autoSort:
v.sort()
# with auto sort no longer necessary.
#s.isSorted = False
# changes elements
# returnObj.elementsChanged()
# if returnObj.autoSort:
# returnObj.sort()
if inPlace is not True:
return returnObj
开发者ID:EQ4,项目名称:music21,代码行数:101,代码来源:makeNotation.py
示例10: cacheMetadata
def cacheMetadata(
corpusNames=('local', 'core', 'virtual'),
useMultiprocessing=True,
verbose=False
):
'''
Cache metadata from corpora in `corpusNames` as local cache files:
Call as ``metadata.cacheMetadata()``
'''
from music21 import corpus
from music21 import metadata
if not common.isIterable(corpusNames):
corpusNames = (corpusNames,)
timer = common.Timer()
timer.start()
# store list of file paths that caused an error
failingFilePaths = []
# the core cache is based on local files stored in music21
# virtual is on-line
for corpusName in corpusNames:
if corpusName == 'core':
metadataBundle = metadata.MetadataBundle.fromCoreCorpus()
paths = corpus.getCorePaths()
useCorpus = True
elif corpusName == 'local':
metadataBundle = metadata.MetadataBundle.fromLocalCorpus()
paths = corpus.getLocalPaths()
useCorpus = False
elif corpusName == 'virtual':
metadataBundle = metadata.MetadataBundle.fromVirtualCorpus()
paths = corpus.getVirtualPaths()
useCorpus = False
else:
message = 'invalid corpus name provided: {0!r}'.format(corpusName)
raise MetadataCacheException(message)
message = 'metadata cache: starting processing of paths: {0}'.format(
len(paths))
if verbose is True:
environLocal.warn(message)
else:
environLocal.printDebug(message)
failingFilePaths += metadataBundle.addFromPaths(
paths,
useCorpus=useCorpus,
useMultiprocessing=useMultiprocessing,
verbose=verbose
)
message = 'cache: writing time: {0} md items: {1}'.format(
timer, len(metadataBundle))
if verbose is True:
environLocal.warn(message)
else:
environLocal.printDebug(message)
del metadataBundle
message = 'cache: final writing time: {0} seconds'.format(timer)
if verbose is True:
environLocal.warn(message)
else:
environLocal.printDebug(message)
for failingFilePath in failingFilePaths:
message = 'path failed to parse: {0}'.format(failingFilePath)
if verbose is True:
environLocal.warn(message)
else:
environLocal.printDebug(message)
开发者ID:folkengine,项目名称:music21,代码行数:72,代码来源:caching.py
示例11: fontFamily
def fontFamily(self, newFamily):
if common.isIterable(newFamily):
self._fontFamily = newFamily
else:
self._fontFamily = [f.strip() for f in newFamily.split(',')]
开发者ID:cuthbertLab,项目名称:music21,代码行数:5,代码来源:style.py
示例12: listOfTimespanTreesByClass
def listOfTimespanTreesByClass(
inputStream,
currentParentage=None,
initialOffset=0,
flatten=False,
classLists=None,
):
r'''
Recurses through `inputStream`, and constructs TimespanTrees for each
encountered substream and ElementTimespans for each encountered non-stream
element.
`classLists` should be a sequence of valid inputs for `isClassOrSubclass()`. One
TimespanTree will be constructed for each element in `classLists`, in
a single optimized pass through the `inputStream`.
This is used internally by `streamToTimespanTree`.
>>> score = timespans.makeExampleScore()
Get everything in the score
>>> trees = timespans.listOfTimespanTreesByClass(score)
>>> trees
[<TimespanTree {2} (-inf to inf) <music21.stream.Score ...>>]
>>> for t in trees[0]:
... print(t)
<TimespanTree {4} (-inf to inf) <music21.stream.Part ...>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 1 offset=0.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 2 offset=2.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 3 offset=4.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 4 offset=6.0>>
<TimespanTree {4} (-inf to inf) <music21.stream.Part ...>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 1 offset=0.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 2 offset=2.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 3 offset=4.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 4 offset=6.0>>
Now filter the Notes and the Clefs & TimeSignatures of the score (flattened) into a list of two timespans
>>> classLists = ['Note', ('Clef', 'TimeSignature')]
>>> trees = timespans.listOfTimespanTreesByClass(score, classLists=classLists, flatten=True)
>>> trees
[<TimespanTree {12} (0.0 to 8.0) <music21.stream.Score ...>>,
<TimespanTree {4} (0.0 to 0.0) <music21.stream.Score ...>>]
'''
if currentParentage is None:
currentParentage = (inputStream,)
## fix non-tuple classLists -- first call only...
if classLists:
for i in range(len(classLists)):
cl = classLists[i]
if not common.isIterable(cl):
classLists[i] = (cl,)
lastParentage = currentParentage[-1]
if classLists is None or len(classLists) == 0:
outputCollections = [trees.TimespanTree(source=lastParentage)]
classLists = []
else:
outputCollections = [
trees.TimespanTree(source=lastParentage) for _ in classLists
]
# do this to avoid munging activeSites
inputStreamElements = inputStream._elements[:] + inputStream._endElements
for element in inputStreamElements:
offset = element.getOffsetBySite(lastParentage) + initialOffset
wasStream = False
if element.isStream and \
not element.isSpanner and \
not element.isVariant:
localParentage = currentParentage + (element,)
containedTimespanTrees = listOfTimespanTreesByClass(
element,
currentParentage=localParentage,
initialOffset=offset,
flatten=flatten,
classLists=classLists,
)
for outputTSC, subTSC in zip(outputCollections, containedTimespanTrees):
if flatten is not False: # True or semiFlat
outputTSC.insert(subTSC[:])
else:
outputTSC.insert(subTSC)
wasStream = True
if not wasStream or flatten == 'semiFlat':
parentOffset = initialOffset
parentEndTime = initialOffset + lastParentage.duration.quarterLength
endTime = offset + element.duration.quarterLength
for classBasedTSC, classList in zip(outputCollections, classLists):
if classList and not element.isClassOrSubclass(classList):
continue
elementTimespan = spans.ElementTimespan(
element=element,
parentage=tuple(reversed(currentParentage)),
#.........这里部分代码省略.........
开发者ID:Wajih-O,项目名称:music21,代码行数:101,代码来源:__init__.py
示例13: getRealized
#.........这里部分代码省略.........
If `useArticulations` is True and client is not None, any articulations
found on that client will be used to adjust the volume. Alternatively,
the `useArticulations` parameter may supply a list of articulations
that will be used instead of that available on a client.
The `velocityIsRelative` tag determines if the velocity value includes
contextual values, such as dynamics and and accents, or not.
>>> s = stream.Stream()
>>> s.repeatAppend(note.Note('d3', quarterLength=.5), 8)
>>> s.insert([0, dynamics.Dynamic('p'),
... 1, dynamics.Dynamic('mp'),
... 2, dynamics.Dynamic('mf'),
... 3, dynamics.Dynamic('f')])
>>> s.notes[0].volume.getRealized()
0.496...
>>> s.notes[1].volume.getRealized()
0.496...
>>> s.notes[2].volume.getRealized()
0.63779...
>>> s.notes[7].volume.getRealized()
0.99212...
velocity, if set, will be scaled by dynamics
>>> s.notes[7].volume.velocity = 20
>>> s.notes[7].volume.getRealized()
0.22047...
unless we set the velocity to not be relative...
>>> s.notes[7].volume.velocityIsRelative = False
>>> s.notes[7].volume.getRealized()
0.1574803...
'''
#velocityIsRelative might be best set at import. e.g., from MIDI,
# velocityIsRelative is False, but in other applications, it may not
# be
val = baseLevel
dm = None # no dynamic mark
# velocity is checked first; the range between 0 and 1 is doubled,
# to 0 to 2. a velocityScalar of .7 thus scales the base value of
# .5 by 1.4 to become .7
if useVelocity:
if self._velocityScalar is not None:
if not self.velocityIsRelative:
# if velocity is not relateive
# it should fully determines output independent of anything
# else
val = self._velocityScalar
else:
val = val * (self._velocityScalar * 2.0)
# this value provides a good default velocity, as .5 is low
# this not a scalar application but a shift.
else: # target :0.70866
val += 0.20866
# only change the val from here if velocity is relative
if self.velocityIsRelative:
if useDynamicContext is not False:
if hasattr(useDynamicContext,
'classes') and 'Dynamic' in useDynamicContext.classes:
dm = useDynamicContext # it is a dynamic
elif self.client is not None:
dm = self.getDynamicContext() # dm may be None
else:
environLocal.printDebug(['getRealized():',
'useDynamicContext is True but no dynamic supplied or found in context'])
if dm is not None:
# double scalare (so range is between 0 and 1) and scale
# t he current val (around the base)
val = val * (dm.volumeScalar * 2.0)
# userArticulations can be a list of 1 or more articulation objects
# as well as True/False
if useArticulations is not False:
if common.isIterable(useArticulations):
am = useArticulations
elif (hasattr(useArticulations, 'classes')
and 'Articulation' in useArticulations.classes):
am = [useArticulations] # place in a list
elif self.client is not None:
am = self.client.articulations
else:
am = []
for a in am:
# add in volume shift for all articulations
val += a.volumeShift
if clip: # limit between 0 and 1
if val > 1:
val = 1.0
elif val < 0:
val = 0.0
# might to rebalance range after scalings
# always update cached result each time this is called
self._cachedRealized = val
return val
开发者ID:willingc,项目名称:music21,代码行数:101,代码来源:volume.py
示例14: getWorkList
def getWorkList(
self,
workName,
movementNumber=None,
fileExtensions=None,
):
r'''
Search the corpus and return a list of filenames of works, always in a
list.
If no matches are found, an empty list is returned.
>>> from music21 import corpus
>>> coreCorpus = corpus.corpora.CoreCorpus()
# returns 1 even though there is a '.mus' file, which cannot be read...
>>> len(coreCorpus.getWorkList('cpebach/h186'))
1
>>> len(coreCorpus.getWorkList('cpebach/h186', None, '.xml'))
1
>>> len(coreCorpus.getWorkList('schumann_clara/opus17', 3))
1
>>> len(coreCorpus.getWorkList('schumann_clara/opus17', 2))
0
Make sure that 'verdi' just gets the single Verdi piece and not the
Monteverdi pieces:
>>> len(coreCorpus.getWorkList('verdi'))
1
'''
if not common.isListLike(fileExtensions):
fileExtensions = [fileExtensions]
paths = self.getPaths(fileExtensions)
results = []
# permit workName to be a list of paths/branches
if common.isIterable(workName):
workName = os.path.sep.join(workName)
workSlashes = workName.replace('/', os.path.sep)
# find all matches for the work name
# TODO: this should match by path component, not just
# substring
for path in paths:
if workName.lower() in path.lower():
results.append(path)
elif workSlashes.lower() in path.lower():
results.append(path)
if results:
# more than one matched...use more stringent criterion:
# must have a slash before the name
previousResults = results
results = []
longName = os.sep + workSlashes.lower()
for path in previousResults:
if longName in path.lower():
results.append(path)
if not results:
results = previousResults
movementResults = []
if movementNumber is not None and results:
# store one ore more possible mappings of movement number
movementStrList = []
# see if this is a pair
if common.isIterable(movementNumber):
movementStrList.append(
''.join(str(x) for x in movementNumber))
movementStrList.append(
'-'.join(str(x) for x in movementNumber))
movementStrList.append('movement' +
'-'.join(str(x) for x in movementNumber))
movementStrList.append('movement' +
'-0'.join(str(x) for x in movementNumber))
else:
movementStrList += [
'0{0}'.format(movementNumber),
str(movementNumber),
'movement{0}'.format(movementNumber),
]
for filePath in sorted(results):
filename = os.path.split(filePath)[1]
if '.' in filename:
filenameWithoutExtension = os.path.splitext(filename)[0]
else:
filenameWithoutExtension = None
searchPartialMatch = True
if filenameWithoutExtension is not None:
# look for direct matches first
for movementStr in movementStrList:
#if movementStr.lower() in filePath.lower():
if filenameWithoutExtension.lower() == movementStr.lower():
movementResults.append(filePath)
searchPartialMatch = False
# if we have one direct match, all other matches must
# be direct. this will match multiple files with different
# file extensions
if movementResults:
continue
#.........这里部分代码省略.........
开发者ID:sbrother,项目名称:music21,代码行数:101,代码来源:corpora.py
示例15: search
def search(self, query=None, field=None, fileExtensions=None, **kwargs):
r'''
Perform search, on all stored metadata, permit regular expression
matching.
>>> workList = corpus.corpora.CoreCorpus().getWorkList('ciconia')
>>> metadataBundle = metadata.bundles.MetadataBundle()
>>> failedPaths = metadataBundle.addFromPaths(
... workList,
... parseUsingCorpus=False,
... useMultiprocessing=False,
... storeOnDisk=False, #_DOCS_HIDE
... )
>>> failedPaths
[]
>>> searchResult = metadataBundle.search(
... 'cicon',
... field='composer'
... )
>>> searchResult
<music21.metadata.bundles.MetadataBundle {1 entry}>
>>> len(searchResult)
1
>>> searchResult[0]
<music21.metadata.bundles.MetadataEntry: ciconia_quod_jactatur_xml>
>>> searchResult = metadataBundle.search(
... 'cicon',
... field='composer',
... fileExtensions=('.krn',),
... )
>>> len(searchResult) # no files in this format
0
>>> searchResult = metadataBundle.search(
... 'cicon',
... field='composer',
... fileExtensions=('.xml'),
... )
>>> len(searchResult)
1
Searches can also use keyword args:
>>> metadataBundle.search(composer='cicon')
<music21.metadata.bundles.MetadataBundle {1 entry}>
'''
if fileExtensions is not None and not common.isIterable(fileExtensions):
fileExtensions = [fileExtensions]
newMetadataBundle = MetadataBundle()
if query is None and field is None:
if not kwargs:
raise MetadataBundleException('Query cannot be empty')
field, query = kwargs.popitem()
for key in self._metadataEntries:
metadataEntry = self._metadataEntries[key]
# ignore stub entries
if metadataEntry.metadata is None:
continue
sp = metadataEntry.sourcePath
if not isinstance(sp, pathlib.Path):
sp = pathlib.Path(sp)
if metadataEntry.search(query, field)[0]:
include = False
if fileExtensions is not None:
for fileExtension in fileExtensions:
if fileExtension and fileExtension[0] != '.':
fileExtension = '.' + fileExtension
if sp.suffix == fileExtension:
include = True
break
elif (fileExtension.endswith('xml')
and sp.suffix in ('.mxl', '.mx')):
include = True
break
else:
include = True
if include and key not in newMetadataBundle._metadataEntries:
newMetadataBundle._metadataEntries[key] = metadataEntry
newMetadataBundle._metadataEntries = OrderedDict(
sorted(list(newMetadataBundle._metadataEntries.items()),
key=lambda mde: mde[1].sourcePath))
if kwargs:
return newMetadataBundle.search(**kwargs)
return newMetadataBundle
开发者ID:cuthbertLab,项目名称:music21,代码行数:91,代码来源:bundles.py
示例16: listOfTreesByClass
def listOfTreesByClass(inputStream,
currentParentage=None,
initialOffset=0.0,
flatten=False,
classLists=None,
useTimespans=False):
r'''
Recurses through `inputStream`, and constructs TimespanTrees for each
encountered substream and PitchedTimespan for each encountered non-stream
element.
`classLists` should be a sequence of valid inputs for `isClassOrSubclass()`. One
TimespanTree will be constructed for each element in `classLists`, in
a single optimized pass through the `inputStream`.
This is used internally by `streamToTimespanTree`.
>>> score = tree.makeExampleScore()
Get everything in the score
>>> treeList = tree.fromStream.listOfTreesByClass(score, useTimespans=True)
>>> treeList
[<TimespanTree {2} (-inf to inf) <music21.stream.Score ...>>]
>>> tl0 = treeList[0]
>>> for t in tl0:
... print(t)
<TimespanTree {4} (-inf to inf) <music21.stream.Part ...>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 1 offset=0.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 2 offset=2.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 3 offset=4.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 4 offset=6.0>>
<TimespanTree {4} (-inf to inf) <music21.stream.Part ...>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 1 offset=0.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 2 offset=2.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 3 offset=4.0>>
<TimespanTree {0} (-inf to inf) <music21.stream.Measure 4 offset=6.0>>
Now filter the Notes and the Clefs & TimeSignatures of the score
(flattened) into a list of two TimespanTrees
>>> classLists = ['Note', ('Clef', 'TimeSignature')]
>>> treeList = tree.fromStream.listOfTreesByClass(score, useTimespans=True,
... classLists=classLists, flatten=True)
>>> treeList
[<TimespanTree {12} (0.0 to 8.0) <music21.stream.Score ...>>,
<TimespanTree {4} (0.0 to 0.0) <music21.stream.Score ...>>]
'''
if currentParentage is None:
currentParentage = (inputStream,)
## fix non-tuple classLists -- first call only...
if classLists:
for i, cl in enumerate(classLists):
if not common.isIterable(cl):
classLists[i] = (cl,)
lastParentage = currentParentage[-1]
if useTimespans:
treeClass = timespanTree.TimespanTree
else:
treeClass = trees.OffsetTree
if classLists is None or not classLists:
outputTrees = [treeClass(source=lastParentage)]
classLists = []
else:
outputTrees = [treeClass(source=lastParentage) for _ in classLists]
# do this to avoid munging activeSites
inputStreamElements = inputStream._elements[:] + inputStream._endElements
for element in inputStreamElements:
offset = lastParentage.elementOffset(element) + initialOffset
wasStream = False
if element.isStream:
localParentage = currentParentage + (element,)
containedTrees = listOfTreesByClass(element,
currentParentage=localParentage,
initialOffset=offset,
flatten=flatten,
classLists=classLists,
useTimespans=useTimespans)
for outputTree, subTree in zip(outputTrees, containedTrees):
if flatten is not False: # True or semiFlat
outputTree.insert(subTree[:])
else:
outputTree.insert(subTree.lowestPosition(), subTree)
wasStream = True
if not wasStream or flatten == 'semiFlat':
parentOffset = initialOffset
parentEndTime = initialOffset + lastParentage.duration.quarterLength
endTime = offset + element.duration.quarterLength
for classBasedTree, classList in zip(outputTrees, classLists):
if classList and not element.isClassOrSubclass(classList):
continue
if useTimespans:
#.........这里部分代码省略.........
开发者ID:willingc,项目名称:music21,代码行数:101,代码来源:fromStream.py
示例17: music21ModWSGIFeatureApplication
#.........这里部分代码省略.........
<table border=0 width='100%'>
<tr><td align='center'>
<table border=0 width='500px' cellpadding='10px' style='background-color:#FFF'>
<tr><td align='left'>
<h1>Music 21 Feature Extraction:</h1>
<p><b>Error:</b> File not in .zip format</p>
<p><a href='/music21/featureapp/uploadForm'>Try Again</a></p>
</td></tr></table>
</td></tr></table>
</body></html>
"""
response_headers = [('Content-type', 'text/html'),
('Content-Length', str(len(html)))]
start_response(status, response_headers)
return [html]
# Setup Feature Extractors and Data Set
ds = features.DataSet(classLabel='Class')
featureIDList = list()
# Check if features have been selected. Else display error
try:
unused_featureFile = formFields['features']
except:
html = """
<html ><body>
<h1>Error:</h1>
<p>No extractors selected</p>
<p><a href='/music21/featureapp/uploadForm'>try again</a></p>
</body></html>
"""
return html
if common.isIterable(formFields['features']):
print(formFields['features'])
for featureId in formFields['features']:
featureIDList.append(str(featureId.value))
else:
featureIDList.append(formFields['features'].value)
fes = features.extractorsById(featureIDList)
ds.addFeatureExtractors(fes)
# Create ZipFile Object
zipf = zipfile.ZipFile(uploadedFile, 'r')
# Loop Through Files
for scoreFileInfo in zipf.infolist():
filePath = scoreFileInfo.filename
# Skip Directories
if(filePath.endswith('/')):
continue
scoreFile = zipf.open(filePath)
# Use Music21's converter to parse file
parsedFile = idAndParseFile(scoreFile,filePath)
# If valid music21 format, add to data set
if parsedFile is not None:
# Split into directory structure and filname
pathPartitioned = filePath.rpartition('/')
directory = pathPartitioned[0]
filename = pathPartitioned[2]
if directory == "":
directory = 'uncategorized'
ds.addData(parsedFile,classValue=directory,id=filename)
# Process data set
ds.process()
# Get output format from POST and set appropriate output:
outputFormatID = formFields['outputformat'].value
if outputFormatID == CSV_OUTPUT_ID:
output = features.OutputCSV(ds).getString()
elif outputFormatID == ORANGE_OUTPUT_ID:
output = features.OutputTabOrange(ds).getString()
elif outputFormatID == ARFF_OUTPUT_ID:
output = features.OutputARFF(ds).getString()
else:
output = "invalid output format"
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
开发者ID:00gavin,项目名称:music21,代码行数:101,代码来源:featureapp.py
注:本文中的music21.common.isIterable函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论