Python split函数将字符混淆为:

2024-04-19 06:09:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读取具有以下字符串的csv文件:

 Allergic granulomatosis angiitis (disorder) ;http://purl.bioontology.org/ontology/SNOMEDCT/;82275008;Drug allergy ;http://purl.bioontology.org/ontology/SNOMEDCT/;414285001;Drug class allergen ;;82275008;Mild;255604002;108

我把它传递给一个python函数,如下所示:

Javascript代码:

function readfile(f) {
var text = ""
var reader = new FileReader();  // Create a FileReader object
reader.readAsText(f);           // Read the file
reader.onload = function() {    // Define an event handler
    text = reader.result;   // This is the file contents
    alert(text);
    var out = document.getElementById("output");    // Find output element
    out.innerHTML = "";                             // Clear it
}
reader.onerror = function(e) {  // If anything goes wrong
    console.log("Error", e);    // Just log it
};

}

function importAllergies() {
    window.location="importAllergies/"+text;
 }

html格式:

Import allergies:
<input type="file" onchange="readfile(this.files[0])"></input>
<pre id="output"></pre> <input id="clickMe" type="button" value="Import" onclick="importAllergies();" />

以及我在视图.py是:

def importAllergies(request,stringP):
    record_id = request.session['record_id']
    INDIVO_IP = settings.INDIVO_IP 
    splitted = stringP.split(';') 
    params = {'allergic_reaction_title': splitted[0],
              'allergic_reaction_system': 'http://purl.bioontology.org/ontology/SNOMEDCT/',
              'allergic_reaction_identifier': splitted[2],
              'category_title': splitted[3]}

你知道吗网址.py地址:

 (r'^bulkimport/importAllergies/(?P<stringP>[^/]+)', importAllergies),

一切正常,除了链接。所以splitted[1]=“http:” 好像把“;”和“:”混淆了。如果我尝试使用splitted[2],也有一个例外:

Exception Type:     IndexError
Exception Value:    

list index out of range

如果我删除链接分裂工作正常。你知道吗


Tags: textorgidhttpvarfunctionoutreader
1条回答
网友
1楼 · 发布于 2024-04-19 06:09:41

对我来说非常好,在你举的例子中:

>>> stringP = "Allergic granulomatosis angiitis (disorder) ;http://purl.bioontology.org/ontology/SNOMEDCT/;82275008;Drug allergy ;http://purl.bioontology.org/ontology/SNOMEDCT/;414285001;Drug class allergen ;http://purl.bioontology.org/ontology/NDFRT/;82275008;Mild;http://purl.bioontology.org/ontology/SNOMEDCT/;255604002;108"
>>> splitted = stringP.split(';')
>>> splitted
['Allergic granulomatosis angiitis (disorder) ', 'http://purl.bioontology.org/ontology/SNOMEDCT/', '82275008', 'Drug allergy ', 'http://purl.bioontology.org/ontology/SNOMEDCT/', '414285001', 'Drug class allergen ', 'http://purl.bioontology.org/ontology/NDFRT/', '82275008', 'Mild', 'http://purl.bioontology.org/ontology/SNOMEDCT/', '255604002', '108']

这就是所有的链接,splitted[2]没有错误,以此类推。所以你不能让我们知道什么对你不利。你知道吗

请编辑您的Q,在>>>解释器提示下重复这三个步骤,复制并粘贴结果(缩进4个空格以使其可读),以确认这一点;然后,让我们看看您在代码中所做的与您在问题中显示的不同之处。你知道吗

编辑:假设bug实际上在正则表达式中

(?P<stringP>[^/]+)'

只需将后者编辑为

(?P<stringP>.+)'

你到底为什么要在第一次/停止匹配?!一直到URL的末尾,事情应该会更好。。。你知道吗

相关问题 更多 >