首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python numpy ndarray从文本中跳过行

Python numpy ndarray从文本中跳过行
EN

Stack Overflow用户
提问于 2016-04-28 20:06:53
回答 3查看 220关注 0票数 0

基于this answer,我使用changethis方法

代码语言:javascript
运行
复制
import numpy as np
import os

def changethis(pos):
    appex = sfile[pos[1]-1][:pos[2]] + '*' + file[pos[1]-1][pos[2]+len(pos[0]):]
    file[pos[1]-1] = appex

pos = ('stack', 3, 16)
sfile = np.genfromtxt('in.cpp',dtype='str',delimiter=os.linesep)
changethis(pos)
print(file)

其中,in.cpp是一个源文件,其中包含以下内容:

代码语言:javascript
运行
复制
/* Multi-line 
comment
*/

#include <iostream>
#include <fstream>

using namespace std;

int main (int argc, char *argv[]) {
  int linecount = 0;
  double array[1000], sum=0, median=0, add=0;
  string filename;
  if (argc <= 1)
      {
          cout << "Error" << endl;
          return 0;
      }

我得到了输出:

代码语言:javascript
运行
复制
['using namespace std;' 'int main (int argc, char *argv[]) {'
 'int linecount = *' 'double array[1000], sum=0, median=0, add=0;'
 'string filename;' 'if (argc <= 1)' '{' 'cout << "Error" << endl;'
 'return 0;' '}']

注意,多行注释include语句空行的行在ndarray中缺失。

我不明白为什么会发生这种情况,因为delimiter被设置为考虑每个行字符的变化。

关于产出如何的任何建议:

代码语言:javascript
运行
复制
['/* Multi-line' 'comment' '*/' '' '#include <iostream>',
 '' '#include <fstream>' '' 'using namespace std;'
 '' 'int main (int argc, char *argv[]) {'
 'int linecount = *' 'double array[1000], sum=0, median=0, add=0;'
 'string filename;' 'if (argc <= 1)' '{' 'cout << "Error" << endl;'
 'return 0;' '}']
EN

Stack Overflow用户

发布于 2016-04-28 20:31:55

如果文件不太大:

代码语言:javascript
运行
复制
import numpy as np
import os

def changethis(linelist,pos):
    appex = linelist[pos[2]-1][:pos[3]] + pos[1] + linelist[pos[2]-1][pos[3]+len(pos[0]):]
    linelist[pos[2]-1] = appex

pos = ('Multi','Three', 1, 3)

with open('in.cpp','r')  as f:
    lines=f.readlines()
    changethis(lines,pos)
print(''.join(lines))

readlines会把你的文件变成一个行列表(内存效率低,速度慢,但是可以完成这项工作)。如果小于1k行,就可以了)。

除了pos之外,该函数还接受行列表作为输入。我还修改了函数,使其使用pos[0]复制pos[1],而不是在pos[2]行和字符pos[3]之后使用*

我得到这个作为输出:

代码语言:javascript
运行
复制
/* Three-line 
comment
*/

#include <iostream>
#include <fstream>

using namespace std;

int main (int argc, char *argv[]) {
  int linecount = 0;
  double array[1000], sum=0, median=0, add=0;
  string filename;
  if (argc <= 1)
      {
          cout << "Error" << endl;
          return 0;
      }
票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36924519

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档