我想打开一个文件,将其内容存储在一个数组中,每次更改一个句子,然后打印文件的输出。
我有这样的事情:
open (FILE , $file);
my @lines = split('.' , <FILE>)
close FILE;
for (@lines) {
s/word/replace/g;
}
open (FILE, ">$file");
print FILE @lines;
close FILE;
出于某种原因,perl不喜欢这样,并且不会将任何内容输出到新文件中。它似乎不喜欢我分裂阵列。有人可以给我一个解释为什么perl会这样做以及可能的修复?谢谢!
答案 0 :(得分:1)
split('.' , <FILE>)
更改为split(/\./ , <FILE>)
答案 1 :(得分:0)
将my @lines = split('.' , <FILE>)
更改为my @lines = split('\.' , <FILE>)
正则表达式中仅使用.
来匹配单个字符。所以你需要逃离.
才能完全分开。
答案 2 :(得分:0)
#!/usr/local/bin/perl
use strict;
use warnings;
my $filename = "somefile.txt";
my $contents = do { local(@ARGV, $/) = $filename; <> };
my @lines = split '\.', $contents;
foreach(@lines){
#lines is an array which contains one sentence at each index.
}
答案 3 :(得分:0)
我发现你的脚本的第二行缺少分号(;),这是错误,而且你的脚本无法处理整个文件的内容。它只会处理一行。所以请在下面找到修改您的脚本。如有任何说明,请告诉我。
my $file='test.txt';#input file name
open (FILE , $file);
#my @lines = split('\.' ,<FILE>); this will not process the entire content of the file.
my @lines;
while(<FILE>) {
s/word/replace/g;
push(@lines,$_);
}
close FILE;
open (FILE, ">$file");
print FILE @lines;
close FILE;
答案 4 :(得分:0)
您的代码中存在很多问题。
my @lines = split('.' , <FILE>)
只会读取第一行并将其拆分。 split('.'
应为split(/\./
my @lines = split('.' , <FILE>)
没有分号终结符。print FILE @lines;
- 你已经失去了所有的全部停留!最后,我不得不想知道为什么你会对“句子”感到困扰。当你刚刚替换一个单词时。如果你真的想一次读一个句子(大概是做某种基于句子的处理),那么你需要改变记录分隔符变量$\
。例如:
#!/usr/bin/perl
use strict;
use warnings;
my $file = "data.txt";
open (FILE , $file);
my @buffer;
$/ = '.'; # Change the Input Separator to read one sentence at a time.
# Be careful though, it won't work for questions ending in ?
while ( my $sentence = <FILE> ) {
$sentence =~ s/word/replace/g;
push @buffer, $sentence;
}
close FILE;
.. saving to file is left for you to solve.
但是,如果您只想更改字符串,则可以通过将$/
设置为undef来一次性读取整个文件。例如:
#!/usr/bin/perl
use strict;
use warnings;
my $file = "data.txt";
open (FILE , $file);
$/ = undef; # Slurp mode!
my $buffer = <FILE>;
close FILE;
$buffer =~ s/word/replace/g;
open (FILE, ">$file");
print FILE $buffer;
close FILE;
如果您真的想要处理句子并且想要获得问题,那么您可能想要整理整个文件然后将其拆分,但在正则表达式中使用捕获,这样您就不会丢失标点符号。例如:
!/usr/bin/perl
use strict;
use warnings;
my $file = "data.txt";
open (FILE , $file);
$/ = undef; # slurp!
my $buffer = <FILE>;
close FILE;
open (FILE, ">$file" . '.new'); # Don't want to overwrite my input.
foreach my $sentence (split(/([\.|\?]+)/, $buffer)) # split uses () to capture punctuation.
{
$sentence =~ s/word/replace/g;
print FILE $sentence;
}
close FILE;