A씨는 개발된 소스코드를 특정업체에 납품하려고 한다. 개발된 소스코드들은 탭으로 들여쓰기가 된것, 공백으로 들여쓰기가 된 것들이 섞여 있다고 한다. A씨는 탭으로 들여쓰기가 된 모든 소스를 공백 4개로 수정한 후 납품할 예정이다.
A씨를 도와줄 수 있도록 소스코드내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램을 작성하시오.
512개의 풀이가 있습니다.
대화형으로 사용할수있게 작성해보았습니다.
해당파일들 위치에 백업파일 생성후 기존파일에 탭을 스페이스로 변환 합니다.
# -*- coding:utf-8 -*-
import os
import re
filepath = input('파일이 위치한 경로를 입력하세요:')
ext = input('확장자를 입력하세요: ' )
'''파일경로와 확장자를 파라메터로 받아서 하위디렉토리 모두 탐색해서 조건에
맞는 파일전체경로를 list 에 담아 리턴한다.'''
def getFileList(filepath,ext):
_filelist = []
for cur, _dirs, files in os.walk(filepath):
for filenm in files:
if (filenm.lower()).endswith(ext.lower()):
_filelist.append(cur+"\\"+filenm)
return _filelist
for _path in getFileList(filepath,ext):
print(_path)
os.system ("copy %s %s" % (_path, _path+".bak")) #백업파일 생성
with open( _path+".bak",'r') as f:
srcContent = f.read()
with open(_path,"w") as writelist:
writelist.write(srcContent.replace("\t"," "))
파이썬 3.4 입니다.
filename=input("Enter your file name : ")
tempfile=open(filename)
tempfile=tempfile.read()
temp_str=tempfile.replace("\t"," ")
tempfile=open(filename,'w')
tempfile.write(temp_str)
tempfile.close()
펄입니다
for(<STDIN>){s/^\t/ /g;print}
리눅스셸에서 다음과 같이 사용 가능
$perl -e 'for(<STDIN>){s/^\t/ /g;print}' <INPUTFILE >OUTPUTFILE
coding by python beginner
import sys, os
f = open( sys.argv[1], 'r' )
t0 = f.read()
f.close()
f = open( sys.argv[1], 'w' )
f.write( t0.replace( '\t', ' ' * 4 ) )
f.close()
os.system( 'cat ' + sys.argv[1] )
static void Main(string[] args)
{
string Text = File.ReadAllText(@"E:\TebTest.txt");
Text = Text.Replace('\t', ' ');
Text = Text.Replace(" ", " ");
Console.WriteLine(Text);
}
#include <stdio.h>
int main(void)
{
char str[] = { "Test\tS\ttring" };
int i = 0;
for (i = 0; i < sizeof(str); i++)
{
if (str[i] == '\t')
{
str[i] = ' ';
}
}
printf("%s\n", str);
return 0;
}
파일입출력은 공부하지 않아서 example string에 포함된 Tab을 Space로 바꾸는 코드를 작성하였습니다.
#import <Foundation/Foundation.h>
BOOL(^ExistFile)(NSString *)=
^(NSString *path){
NSFileManager * tmpManager = [ NSFileManager defaultManager ];
if( [ tmpManager fileExistsAtPath:path ] )
return YES;
return NO;
}; // 파일 존재여부 확인
NSData *(^TabToSpace)(NSData *)=
^(NSData *current){ // 입력받은 문자, 탭, 공백을 NSString으로 변환해서 비교/작업
NSString * buf = [ NSString stringWithUTF8String: [ current bytes ] ];
NSString * tab = [ NSString stringWithFormat:@"\t" ];
NSString * change = [ NSString stringWithFormat:@" " ];
if( tab == buf )
current = [ change dataUsingEncoding:NSUTF8StringEncoding ];
return current;
}; // current가 탭인지 확인해서 맞다면 공백 반환, 아니면 그대로 반환
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSFileManager * myManager = [ NSFileManager defaultManager ]; // 파일 제어 관련
NSString * path =
[ NSString
stringWithFormat:
@"/Users/outlt/Desktop/outlt/Stamp/TabToSpace/TabToSpace/" ]; // 파일 다룰 경로
NSString * file1 = [ NSString stringWithString:
[ path stringByAppendingString:@"tab.txt" ] ]; // 파일이름 ( 원본 )
NSString * file2 = [ NSString stringWithString:
[ path stringByAppendingString:@"result.txt" ] ]; // 파일이름 ( 탭제거후 )
[ myManager createFileAtPath:file2 contents:nil attributes:nil];
// 새로운 파일 생성
if( !( ExistFile(file2) && ExistFile(file1) ) ){
NSLog(@" 파일이 없음"); return 1;
} // 파일 2개 존재 확인
NSFileHandle * file =
[ NSFileHandle fileHandleForReadingAtPath: file1 ]; // 원본파일을 읽기로 열기
NSFileHandle * result =
[ NSFileHandle fileHandleForWritingAtPath:file2 ]; // 만든파일을 쓰기로 열기
unsigned long long mySeek = [ file seekToEndOfFile ] ; // 파일 내용의 용량
[ file seekToFileOffset:0 ]; // 파일포인터를 맨뒤로 보내서 파일용량을 확인했으므로 다시 처음으로
while ( [ file offsetInFile ] < mySeek ) // 파일의 마지막까지 1바이트씩
{
NSData * data = [ file readDataOfLength:1]; // 1바이트 읽기
[ result writeData: TabToSpace(data) ]; // 쓰기
}
}
return 0;
}
// C# 입니다.
using System;
class Program
{
static string input = "\ttab\t\ttabtab";
static void Main()
{
string output = input.Replace("\t", " ");
Console.WriteLine(input);
Console.WriteLine(output);
}
}
package change_tab_to_blank;
import java.io.*;
public class changetab {
public static void main(String[] args)
{
try{
//파일로부터 입력받음
File input_file = new File("input.txt");
FileReader fileReader = new FileReader(input_file);
BufferedReader reader = new BufferedReader(fileReader);
//출력 대상 파일 설정
FileWriter fileWriter = new FileWriter("output.txt");
BufferedWriter writer = new BufferedWriter(fileWriter);
int input_ascii;
while( ( input_ascii = reader.read() ) != -1 ){
//문자하나하나는 아스키로 받아와서 char형으로 변환하여 사용
char input_char = (char)input_ascii;
if( input_char == 9 ){
//tab의 아스키코드는 9, 공백의 아스키코드는 32
input_char = 32;
//탭만나면 공백 4번
for( int i=1; i<=4; i++){
writer.write( input_char );
//System.out.print(input_char);
}
}
else{ //탭 아닌 다른 문자들은 그냥 그대로 출력
writer.write( input_char );
//System.out.print(input_char);
}
}
writer.close(); //안닫아주면 안됨
reader.close();
}
catch(Exception ex){
}
}
}
f = open("./aaa.txt.", 'r') # 소스코드가 aaa 파일에 있다고 가정
lines = f.readlines()
f.close()
f = open("./bbb.txt", 'w') # 수정할 코드를 bbb 파일에 저장
for line in lines:
f.write(line.replace("\t", " "))
f.close()
filename = input('write filname : ')
with open(filename, 'r') as f:
f = f.read()
a = f.replace("\t"," ")
with open(filename,'w') as f:
f.write(a)
#tts.py
import sys
def usage():
print("Usage: python %s filename" % sys.argv[0])
try: f = open(sys.argv[1])
except: usage(); sys.exit(2)
msg = f.read()
msg = msg.replace('\t'," "*4)
f.close()
f = open(sys.argv[1], 'w')
f.write(msg)
f.close()
파이썬 입니다.
# cod_tabto4.py
import re
import sys
def tab_to_space(file_name):
source_cod = file_name.read()
file_name.close()
patturn = re.compile(r'\t')
changed = patturn.sub(" ", source_cod)
file_name = open(sys.argv[1],'w')
file_name.write(changed)
file_name.close()
try:
file_name = open(sys.argv[1])
tab_to_space(file_name)
except:
print("Usage: python %s filename" % sys.argv[0])
sys.exit(2)
import re
import sys
def usage():
print("Usage: python %s filename [no. of space]" % sys.argv[0])
try:
f = open(sys.argv[1])
except:
usage(); sys.exit(2)
msg = f.read()
f.close()
p = re.compile(r'\t')
changed = p.sub(" "*int(sys.argv[2]), msg)
f = open(sys.argv[1], 'w')
f.write(changed)
f.close()
python 입니다.
import unittest
def method1(str):
return str.replace('\t', ' ')
class TestTab2Space(unittest.TestCase):
def test_method1(self):
str = "Hello\tMy Friend."
self.assertEqual(method1(str), "Hello My Friend.")
if __name__ == "__main__":
unittest.main()
public class ChangeSpaceFromTab {
//소스코드내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램
public static void main(String[] args) {
String text = "Today is a gift\tTomorrow is a mistery\tby Kung fu panda.";
String replaceSpaceFromTab = replaceSpaceFromTab(text);
System.out.println(replaceSpaceFromTab);
}
private static String replaceSpaceFromTab(String text) {
String replaceAll = text.replaceAll("\t", " ");
return replaceAll;
}
}
자바 내장함수 replaceAll 사용했습니다.
public class T {
public static void main(String[] args) {
String str="aaa\taaa\taaa";
System.out.println(str);
str=str.replaceAll("\t"," ");
System.out.println(str);
}
}
string = "haha my name is sauron\n"
def changeTabToSpace():
newString = ""
for char in string:
if char == '\t':
char = ' '
newString+=char
return newString
newString = changeTabToSpace()
print string,"\n",newString
replace안쓰고 파일 입출력 제외한 파이썬코드
//bin 경로에 tab.txt 파일 작성 후 테스트. 한글 가능
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class TabToSpaceMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
tabChange(TabToSpaceMain.class.getResource("").getPath(), "tab.txt");
}
public static void tabChange(String filePath, String filename) {
String s = "";
String sNew = "";
BufferedReader bf = null;
BufferedWriter bw = null;
try {
bf = new BufferedReader(new InputStreamReader(new FileInputStream(filePath + filename),"euc-kr"));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath + "new_" + filename)));
while((s = bf.readLine()) != null) {
sNew = s.replaceAll("\t", " ");
bw.write(sNew);
bw.newLine();
}
bf.close();
bw.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
파이썬 2.7입니다. 소스코드에 한글이 없길 기도하며....
def convertTap(str,rep=' ',count=4):
return str.replace('\t',rep*count)
def process(filepath):
with open(filepath, 'rw') as f:
transformed = convertTap(f.read())
f.write(transformed)
import sys
def main():
if len(sys.argv) > 1:
for filepath in sys.argv[1:]:
process(filepath)
if __name__ == "__main__":
main()
파이썬 3.4 입니다.
#tab_to_4_space.py
#vim을 활용한 python프로그램
#코딩도장 lv.1 탭을 공백문자 4개로 바꾸기
def conv_tab(text):
result = text.replace("\t"," ")
return result
text = input("변환할 문자열")
print(conv_tab(text))
먼저 파일 이름을 입력받습니다. 그리고 새로 작성할 파일이름을 만듭니다.
file_name=raw_input("file_inputname:")
new_file_name=file_name +"_new"
파일을 열고
f=open(file_name,'r')
file=f.readlines()
new_f=open(new_file_name,'w')
탭을 공백으로 치환합니다. 그리고 파일을 닫습니다.
for i in file:
test=i.replace("\t"," ")
new_f.write(test)
f.close()
new_f.close()
초보라,, 동작은 됩니다.
file = input("type the target file: ")
f = open(file)
msg = f.read()
f.close()
f = open(file,'w')
f.write(msg.replace("\t", " "))
f.close()
자바 입니다. replaceAll을 굳이 쓰지 않고 replace를 써도 전체 tab이 바뀝니다. 그리고, 눈으로 확인하는 것 보다 Test코드 통과 여부를 보면 좋을 것 같아서 테스트코드도 함께 넣습니다.
public class Tab2Space {
/**
* Tab -> Space(4blank)
* @param originStr
* @return
*/
public String convertTab2Space(String originStr){
String returnString = null;
if (originStr != null) {
returnString = originStr.replace("\t", " ");
}
return returnString;
}
}
아래는 테스트 코드 입니다.
import static org.junit.Assert.*;
import org.junit.Test;
public class Tab2SpaceTest {
@Test
public void testConvertTab2Space() {
String originString = "abc\tdef";
String expectedString = "abc def";
String actualString = new Tab2Space().convertTab2Space(originString);
assertEquals(expectedString, actualString);
}
@Test
public void testConvertTwoTab2Space() {
String originString = "abc\t\tdef";
String expectedString = "abc def";
String actualString = new Tab2Space().convertTab2Space(originString);
assertEquals(expectedString, actualString);
}
@Test
public void testEmptyConvert(){
String originString = null;
String expectedString = null;
String actualString = new Tab2Space().convertTab2Space(originString);
assertEquals(expectedString, actualString);
}
}
Python
import sys
# 시스템 매개변수로 파일명 받아서 처리
args = sys.argv[1:]
filename = args[0]
try:
with open(filename, 'rb') as tab_file:
source = tab_file.readlines() # 파일내 글 모두 읽는다.
target = "".join(source) # 읽어온 데이터는 list 타입이라 스트링으로 변환
target = target.replace("\t", " ") # 탭을 공백으로 변환
with open('space4.txt','wb') as space_file:
space_file.write(target) # 새로운 파일에 저장
except IOError as err:
print('File error: ' + str(err))
def tabToSpace(input: String): String = {
val pattern = "^(\t+)".r
pattern.replaceAllIn(input, { m =>
m.subgroups.map(_.replace("\t", " ")).mkString("")
})
}
println(tabToSpace("\ttest"))
println(tabToSpace("\t\ttest"))
println(
io.Source.fromFile("TabToSpace.scala").getLines.map(tabToSpace).mkString("\n")
)
import sys
import re
def tabto4(filename):
f = open(filename)
txt = f.read()
p = re.compile(r'\t')
txt = p.sub(" "*4, txt)
f.close()
f = open(filename, "w")
f.write(txt)
f.close()
if __name__ == "__main__":
tabto4(sys.argv[1])
#tab to 4space
import re
import sys
def tabToSpace():
print "file name" % sys.argv[0]
try : f = open(sys.argv[1])
except : tabToSpace(); sys.exit(2)
code = f.read()
f.close()
changedCode = code.replace("\t", " "*4)
f = open(sys.argv[1] , 'w')
f.write(changedCode)
f.close()
using python
f = open("tap.txt","r").read()
f = f.replace("\t"," ")
g = open("tap.txt","w")
g.write(f)
g.close()
PHP
<?php
$get = fgets(STDIN); // 내용을 불러온다.
echo preg_replace("/\t/", " ", $get); // $get에서 'Tab'을 ' '로 변환시킨다
?>
간단하게 되네요.
김명훈님 방법보고 따라서 만들어봤어요 ! os.walk !강력하면서 아직 좀 어렵네요 ㅠㅠ
import os
import shutil
import re
filepath=raw_input("directory")
ext=raw_input("ext")
"""원하는 디렉토리 안의 확장자 파일을 리스트로 받는다"""
def getFileList(filepath,ext):
_filepath=[]
for root,dirpath,filename in os.walk(filepath):
for file1 in filename:
if os.path.splitext(file1)[-1]==ext:
_filepath.append(root+"/"+file1)
return _filepath
""" tab을 로 바꿔주는 함수"""
def tab_to_space(text):
text2=text.replace("\t"," ")
return text2
Filelist=getFileList(filepath,ext)
for files in Filelist:
shutil.copyfile(files,files+".dat")
f=open(files,"w")
g=open(files+".dat","r")
f.write(tab_to_space(g.read()))
f.close()
My.Computer.FileSystem.WriteAllText("Path", My.Computer.FileSystem.ReadAllText("Path").Replace(Chr(9), Space(4)), False)
읽어온뒤 바로 수정후 저장을합니다.
일단 스캐너로 문자열을 입력받고 이것을 문자배열로 바꾼후 반복문을통해 문자중 일반 문자는 그대로 출력하고 탭키를 만날시 이것을 스페이스바4개로 출력하게 만들었습니다 처음엔 배열값자체에 넣은후 한번에 출력하려고 하였으나 String과 char형의 타입이 맞지않아 이런식으로 짜보았습니다.
package dojavn;
import java.util.Scanner;
public class dsa {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String ta=sc.nextLine();
char [] s=ta.toCharArray();
for(int i=0;i<s.length;i++)
{
if(s[i]=='\u0009'){
System.out.print(" ");
}
else{
System.out.print(s[i]);
}
}
}
}
import java.io.*;
public class TabTo4Spaces {
String orgDir = "C:/docs";
String descDir = "C:/docs2";
public static void main(String[] args) throws Exception {
TabTo4Spaces tt4 = new TabTo4Spaces();
tt4.convert(new File(tt4.orgDir));
}
public void convert(File file) throws IOException{
if (file.isDirectory()) {
String path = file.getAbsolutePath().replace("\\", "/");
String newPath = path.replace(orgDir.replace("\\", "/"), descDir);
File newDir = new File(newPath);
newDir.mkdir();
if (!newDir.exists()) {
newDir.mkdir();
}
File[] files = file.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory() || pathname.getName().contains("txt");
}
});
for (File f : files) {
convert(f);
}
} else {
tabTo4Spaces(file);
}
}
public void tabTo4Spaces(File org) throws IOException {
String orgParentPath = org.getParent().replace("\\", "/");
String newPath = orgParentPath.replace(orgDir.replace("\\", "/"), descDir);
BufferedReader br = new BufferedReader(new FileReader(org));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(newPath+"/"+org.getName())));
String line = null;
while ((line = br.readLine()) != null) {
bw.write(line.replaceAll("\\t", " "));
bw.newLine();
}
bw.close();
br.close();
}
}
지정된 root디렉토리부터 하위 디렉토리를 재귀함수로 돌려 txt 파일만 변환했습니다. 코드가 지저분... 다시 정리 해야겠네요;
#include "stdafx.h"
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream fin;
ofstream fout;
fin.open("Original.txt");
fout.open("Fixed.txt");
vector<string> arString;
while(!fin.eof())
{
string strTemp;
getline(fin, strTemp);
arString.push_back(strTemp);
}
for (int i = 0; i < (int)arString.size(); ++i)
{
string strTemp = arString[i];
if (strTemp[0] == '\t')
{
strTemp.erase(0, sizeof(char));
strTemp.insert(0, " ");
}
fout << strTemp << endl;
}
int a= 0;
fin.close();
fout.close();
return 0;
}
<?php
// \t ->   * 4;
$temp_str = "내 용 ** 내용";
$temp_str = str_replace("\t","    ",$temp_str);
echo $temp_str;
?>
replace 몰랐음. 콘솔로 확인 후 파일 저장
def swap():
f = open('test.txt','r')
print 'before'
for data in f.readlines():
print data,
print ('')
# Pointer rewind
f.seek(0)
new_f = open('changed.txt','w')
print 'after'
for data in f.readlines():
if data.startswith('\t'):
chs = data[1:]
space = ' ' + chs
print space,
else:
print data,
new_f.write(space)
f.close()
가장 편한것은 command line에서,
expand -t 4 input_file > output_file
sed 사용 가능하면
sed $'s/\t/ /g' input_file > output_file
inplace원하면, vim에서
:%s/\t/ /g
혹은 sed에 -i를 씀
sed -i $'s/\t/ /g' input_file
static void Main(string[] args)
{
string text = File.ReadAllText(@"E:\TebTest.txt");
text = text.Replace('\t', ' ');
text = text.Replace(" ", " ");
Console.WriteLine(text);
}
파이썬입니다. expandtabs 함수를 사용했습니다.
input_file = open('tab.txt', 'r')
output_file = open('space.txt', 'w')
def tabToSpace(text): # 탭을 스페이스 4개로 바꾸는 함수
return text.expandtabs(4)
text = input_file.read()
output_file.write(tabToSpace(text))
input_file.close()
output_file.close()
//php
$file = fopen('./dojang.txt', 'r+'); while(!feof($file)) { $modi_file .= fgets($file); } fclose($file);
$modi_file = str_replace('\t', ' ', $modi_file);
$file = fopen('./m_dojang.txt', 'w'); fwrite($file, $modi_file);
python3입니다. processDir()의 인자로 소스코드 디렉토리를 받도록 했습니다.
import os
def tab2space(filepath):
fp = open(filepath, 'r')
content = fp.read().replace("\t", " " * 4)
fp.close()
fp = open(filepath, "w")
fp.write(content)
fp.close()
def processDir(targetDir):
for (root, _, files) in os.walk(targetDir):
for file in files:
tab2space(os.path.join(root, file))
#include <stdio.h>
int main(int argc,char *argv[]){
FILE *fp,*ap;
int i;
char a;
if((fp=fopen(argv[1],"r"))==NULL)
printf("오류:%s파일을 열수 없습니다.\n",argv[1]);
if((ap=fopen(argv[2],"w"))==NULL)
printf("오류:%s파일을 열수 없습니다.\n",argv[2]);
while((a=getc(fp))!=EOF){
if(a=='\t'){
a=' ';
for(i=0;i<3;i++){
putc(a,ap);
}
}
putc(a,ap);
}
fclose(fp);
fclose(ap);
return 0;
}
c언어 초보입니다 훈수부탁드립니다!!
파이썬 2.7.11
with open('test.txt') as f: s = f.read() s1 = s.replace('\t', ' ')
with open('test1.txt', 'w') as f: f.write(s1)
import re
import sys
def insert():
print("%s filename" % sys.argv[0])
try:
f = open(sys.argv[1])
except:
insert(); sys.exit(2)
msg = f.read()
f.close()
p = re.compile(r'\t')
changed = p.sub(" "*4, msg)
f = open(sys.argv[1], 'w')
f.write(changed)
f.close()
하나하나씩 분석해보도록 하겠습니다.
filename=input("Enter your file name : ") // 이 줄은 input함수를 통해 키보드로부터 데이터를 입력받고 filename 변수에 저장합니다. tempfile=open(filename) // 키보드로부터 입력받은 데이터를 filename에 저장하고 temfile에 저장하고 파일을 오픈합니다. tempfile=tempfile.read() 오픈된 파일을 읽고 있습니다. temp_str=tempfile.replace("\t"," ") //여기서 문제에서 나온 \t개행문자를 공백문자 4개로 치환해주고있습니다. tempfile=open(filename,'w') // 여기서는 temfile을 쓰기모드로 오픈합니다. tempfile.write(temp_str) // temfile을 temp_str에서 수정한 내용을 복사하고있습니다. tempfile.close() // 파일을 닫습니다.
filename=input("Enter your file name : ") tempfile=open(filename) tempfile=tempfile.read() temp_str=tempfile.replace("\t"," ") tempfile=open(filename,'w') tempfile.write(temp_str) tempfile.close()
python 3.4
fname = input("Enter a file name :")
fhand = open(fname)
full_file = fhand.read().replace('\t',' ')
fhand = open(fname,'w')
fhand.write(full_file)
fhand.close()
import sys
text = open(sys.argv[1],'r').read().replace('\t',' ')
f=open(filename,'w')
f.write(text)
f.close()
# encoding=utf-8
save_f = open('text.txt', 'w+')
with open('test.txt', 'r') as f:
for line in f.read():
save_f.write(line.replace('\t',' '*4))
Python newbie
tabFile = open("test.txt")
tmp = tabFile.read()
tabFile.close()
tmp = tmp.replace("\t", " ")
spaceFile = open("test_new.txt", "w")
spaceFile.write(tmp)
spaceFile.close()
p = '경로'
with open(p, 'r') as temp:
r = temp.read().replace('\t',' '*4)
with open(p, 'w') as ed:
ed.write(r)
파이썬 3.5.1입니다.
파이썬
def update(file):
new_line = ''
fin = open(file, 'rt')
while True:
line = fin.readline()
if not line:
break
new_line += line.replace('\t', ' ' * 4, 100)
#한 라인에 탭이 여러번 있을 수 있으므로 세번째 인자로 100번을 시행
fin.close()
fout = open(file, 'wt')
fout.write(new_line)
fout.close()
파이썬3.4
file = input()
with open(file) as filee:
s = filee.read()
s = s.replace('\t',' ')
with open(file, 'w') as filee:
filee.write(s)
Ruby
conv = ->code { code.gsub("\t", " ") }
cleanse = ->src { File.open(src,'r+') {|f| f.write(conv[File.read(src)]) } }
#=> cleanse["source file"]
Test
expect(conv["\t"]).to eq " "
C#으로 작성했습니다.
public string PrintToSpaces(string input)
{
return input.Replace("\t", " ").Replace(" ",string.Empty.PadLeft(4));
}
out_filename = "result.py"
filename = input("filename: ")
try:
with open(filename) as f:
data = f.read()
with open(out_filename, 'w') as new_file:
new_file.write(data.replace('\t', ' '))
print("write ", out_filename)
except IOError as error:
print(str(error))
import os
def tab_to_space(path, ext='py', space_count=4):
def _update(full_path):
with open(full_path, 'r+') as f:
new_code = _tab_to_space(f.read())
f.seek(0)
f.write(new_code)
_tab_to_space = lambda code: code.replace('\t', ' ' * space_count)
dot_ext = '.' + ext
[_update(os.path.join(dp, fn)) for dp, dn, fns in os.walk(path) for fn in fns if not dn and fn.endswith(dot_ext)]
the_file = open("the_file.txt", "r")
new_file = open("new_file.txt", "w")
lines = ''
for text in the_file.readlines():
for t in text:
if t == '\t':
lines += ' '
else:
lines += t
new_file.write(lines)
the_file.close()
new_file.close()
파이썬입니다.
open('output.txt', 'w').write(''.join([x.replace('\t', ' ' * 4) for x in open('input.txt', 'r').readlines()]))
자바로 만들었습니다 .. 매우 단순합니다..
package javaCoding;
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List;
public class Coding003 {
public static void main(String[] args) {
FileReader file=null;
BufferedReader buffer=null;
String AA=null;
StringBuffer BB=new StringBuffer();
try {
//경로 읽기.
file=new FileReader("D:/sdf.txt");
//읽고 나는 버퍼더 리더에 넣을꺼다.
//왜 ?? file의 읽은 값을 받아들이는 것줄에 버퍼더리더가 아주 바람직함.
buffer=new BufferedReader(file);
//버퍼.리드라인 = 택스트에 한줄한줄 읽음서 유무를 확인하면서 .. 스트링 빌더에 넣고있음.
while((AA=buffer.readLine())!=null) {
BB.append(AA);
}
//BB.indexOf(" ") =>텝하나를 의미함..
while((BB.indexOf(" ")>0)) {
BB.replace(BB.indexOf(" "),BB.indexOf(" ")+1," ");
}
System.out.println(BB);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/////////////////////////////////////////////////////////////////////
//위 바꾼 값을 txt로 다시 새롭게 만들기.
//스트링 버퍼의 값을 to스트링을 통해서 스트링으로 변환 해줌 ..
String txt=BB.toString();
//경로
String txt2="D:/hahah.txt";
//경로 파일에 담기
File file2=new File(txt2);
try {
//파일 쓰기
FileWriter file3=new FileWriter(file2);
//값입력
file3.write(txt);
//넣고
file3.flush();
//닫고
file3.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Java로 작성된 코드입니다.
import java.util.Scanner;
public class TabToSpace {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
str.replaceAll("\t", " ");
System.out.println(str);
}
}
package main
import (
"io/ioutil"
"bytes"
"os"
"fmt"
)
func main() {
var in_file, out_file string
fmt.Print("Input File Name: ")
fmt.Scan(&in_file)
fmt.Print("Output File Name: ")
fmt.Scan(&out_file)
if rb, error := ioutil.ReadFile(in_file); error == nil {
wb := []byte(rb)
wb = bytes.Replace(wb, []byte("\t"), []byte(" "), -1)
ioutil.WriteFile(out_file, wb, os.ModePerm)
}
}
Scanner scan = new Scanner(System.in);
System.out.println("문자를 입력해주세요");
String text = scan.nextLine();
text = text.replaceAll("\t", " ");
System.out.println(text);
package 코딩도장;
public class Q4 {
public static void main(String[] args){
String text = "Good\tSoGood\t";
String replace = text.replaceAll("\t", " ");
System.out.println(text);
System.out.println(replace);
}
}
Python
def code(c):
for i in c:
if i=="\t":
c.replace(i," ")
else:
pass
print(c)
code("여기에\t코드를\t붙여넣으면\t됨")
자바로 코딩
1. reaplce
2. char 배열에 저장 해서 출력
public static void main(String[] args){
try{
String tab = "테스트 입니다 ";
tab = tab.replace("\t", " ");
char[] ch = tab.toCharArray();
for(int i=0; i<ch.length; i++){
System.out.print( i + " " + " :: ==> " + (int)ch[i] + "\t" + " || ");
System.out.print( i + " " + " :: ==> " + ch[i] );
System.out.println("");
}
}catch(Exception e){
e.printStackTrace();
}
}
자바로 코딩
파일을 읽는 다는 가정하에 만들었습니다.
public static void main(String[] args){
try{
// 파일 읽기
File file = new File("c:\\test.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
BufferedReader br = new BufferedReader(isr);
// 파일 쓰기
FileOutputStream fos = new FileOutputStream("c:\\test1111.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
String str = "";
while( (str=br.readLine()) != null ){
str = str.replace("\t", " ");
osw.write(str);
osw.write("\n");
}
// close
fis.close();
isr.close();
br.close();
osw.close();
}catch(Exception e){
e.printStackTrace();
}
}
private static String source="Source\tEx\tcoingdojang\tzzz";
public static void main(String[] args) {
System.out.println(source);
System.out.println(source.replace("\t"," "));
}
var str = "안녕하세요. ㅋㅋㅋㅋㅋㅋ ㅎㅎㅎㅎㅎㅎㅎ";
// tab이 포함된 문자열인지 확인
// 결과값 : true
console.log(/\t/gi.test( str ));
// 공백(space) 포함된 문자열인지 확인
// 결과값 : false
console.log(/ /gi.test( str ));
// tab -> space 4번으로 변경
str = str.replace(/\t/gi, " ");
// 결과값 : false
console.log(/\t/gi.test( str ));
// 결과값 : true
console.log(/ /gi.test( str ));
python 3.5
def change_tab_to_space(src):
with open(src, 'r') as f:
data = f.read()
with open(src, 'w') as f:
f.write(data.replace("\t", " "*4))
change_tab_to_space("a.txt")
def TabToSpaceConverter(orginalSouce):
newSource = ""
for i in orginalSouce:
if i == '\t':
newSource += " "
else:
newSource += i
return newSource
print(TabToSpaceConverter(source))
#include <iostream>
#include <string>
#include <algorithm>
std::string sample = "haha\tnice to meet\tyou";
int main() {
std::cout << sample << std::endl;
while (sample.find("\t") != std::string::npos)
{
sample = sample.replace(sample.find("\t"), 1, " ");
}
std::cout << sample << std::endl;
return 0;
}
c++ 작성
#include <stdio.h>
int main(){
FILE* pfa;
FILE* pfb;
pfa = fopen("a.c", "r");
pfb = fopen("b.c", "w");
char c;
while((c = getc(pfa)) != EOF){
if(c == '\t'){
putc(' ', pfb);
putc(' ', pfb);
putc(' ', pfb);
putc(' ', pfb);
} else {
putc(c, pfb);
}
}
fclose(pfb);
fclose(pfa);
}
import re
import sys
def insert():
print("%s filename" % sys.argv[0])
try:
f = open(sys.argv[1])
except:
insert(); sys.exit(2)
msg = f.read()
f.close()
p = re.compile(r'\t')
changed = p.sub(" "*4, msg)
f = open(sys.argv[1], 'w')
f.write(changed)
f.close()
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TabtoWhiteSpace {
public static void main(String args[]) {
String path = "C:/Users/woo/workspace/20161006/test.txt";
String path2 = "C:/Users/woo/workspace/20161006/out.txt";
try{
BufferedReader in = new BufferedReader(new FileReader (path));
BufferedWriter out = new BufferedWriter(new FileWriter (path2));
String s;
while ((s = in.readLine()) != null) {
if(s.contains("\t")) {
s = s.replace("\t", " ");
out.write(s+"\r\n");
} else {
out.write(s+"\r\n");
//out.write("hello world");
}
}
out.close();
}
catch(IOException e) {
System.err.println(e);
System.exit(1);
}
}
}
파이썬
import sys
fromFile = sys.argv[1]
toFile = sys.argv[2]
f = open(fromFile)
origin_content = f.read()
f.close()
replace_content = origin_content.replace("\t", " " * 4)
f = open(toFile, 'w')
f.write(replace_content)
f.close
f = open("D:/python/test.txt", 'r')
while True:
line = f.readline()
if not line: break
if line[0] == "\t":
line = " " + line[1:]
print(line)
f.close()
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main ()
{
string temp;
vector<string> v_temp;
ifstream fin;
ofstream fout;
fin.open("insert.txt");
fout.open("result.txt");
while(!fin.eof()) {
getline(fin, temp);
v_temp.push_back(temp);
}
for (int counter = 0; counter < v_temp.size(); counter++) {
temp = v_temp[counter];
if (temp[0] == '\t') {
temp.erase(0, '\t');
temp.insert(0," ");
}
fout << temp << endl;
}
fin.close();
fout.close();
return 0;
}
Java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
public class TabToSpaceTester {
public static UnaryOperator<String> precedingTabToSpace = s -> {
if (s == null || s.length() == 0) return s;
StringBuffer result = new StringBuffer();
boolean isPrecedingTab = s.startsWith("\t");
int pos = 0;
while (isPrecedingTab && pos < s.length() && s.charAt(pos) == '\t') {
result.append(" ");
pos++;
}
if (pos < s.length() - 1) {
result.append(s.substring(pos));
}
result.append(System.lineSeparator());
return result.toString();
};
public static Consumer<Path> convertFile = p -> {
File tempFile = new File(p.toString() + ".tmp");
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile)))) {
try (Stream<String> stream = Files.lines(p)) {
stream.map(precedingTabToSpace)
.forEach(line -> {
try { writer.write(line); } catch (IOException e) { e.printStackTrace(); }
});
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
if (p.toFile().delete()) {
tempFile.renameTo(p.toFile());
} else {
tempFile.delete();
}
};
public static void main(String[] args) throws IOException {
try (Scanner sc = new Scanner(System.in)) {
Path srcPath = Paths.get(sc.nextLine());
Files.walk(srcPath).filter(p->p.toFile().isFile()).forEach(convertFile);
}
}
}
탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는...
먼저 복사하는 프로그램.
int main(int argc, const char * argv[]) {
int c;
while ((c=getchar()) != EOF) {
putchar(c);
}
return 0;
}
그럼 탭을 공백 4개로..
if (c == '\t') {
putchar(' ');
putchar(' ');
putchar(' ');
putchar(' ');
} else {
putchar(c);
}
Replace 메소드 안쓰고 짜봤습니다. 각 줄 소스 앞의 탭만 제거
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class ReplaceTap {
public static void main(String[] args) {
}
public String[] replaceTap(final String[] codes) {
String[] result = new String[codes.length];
final String blank = " ";
for (int stringIndex = 0; stringIndex < codes.length; stringIndex++) {
int count = 0;
int codeStart = 0;
result[stringIndex] = new String();
for(int i = 0; i < codes[stringIndex].length(); i++) {
char ch = codes[stringIndex].charAt(i);
if(ch == '\t') {
count++;
codeStart = i;
} else
break;
}
for(int i = 0; i < count; i++)
result[stringIndex] += blank;
result[stringIndex] += codes[stringIndex].substring(codeStart + 1);
}
return result;
}
@Test
public void testReplaceTap() {
String[] code = new String[] {"\tprint()" , "\t\texit()"};
String[] expectedString = new String[] {" print()", " exit()"};
assertArrayEquals(expectedString, replaceTap(code));
}
}
def convert_tab_to_space(src, dest):
''' 텍스트파일의 탭문자를 공백문자 4개로 바꾼다 '''
with open(src, 'r', encoding='utf-8') as source:
txt = source.read()
with open(dest, 'w', encoding='utf-8') as destination:
destination.write(txt.replace('\t', ' '))
import re
def replaceTab(source):
p = re.compile(r'^(\t+)', re.M)
return p.sub(lambda m:m.group(1).replace('\t', ' '), source)
String str="aaa\taaa\taaa";
String strResult = "";
System.out.println(str);
for(int i = 0; i < str.length(); i++){
strResult += ('\t' == str.charAt(i))?" ":str.charAt(i);
}
System.out.println(strResult);
Scanner로 입력받은 문자열을 replaceAll 메소드로 변경
import java.util.Scanner;
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("Input:");
Scanner obj=new Scanner(System.in);
String str=obj.nextLine();
System.out.println("Before:"+str);
str=str.replaceAll("\t", " ");
System.out.println("After"+str);
}
}
Haskell
import System.Environment
import Control.Monad
tabToSpace line =
case line of
'\t':xs -> " " ++ (tabToSpace xs)
otherwise -> line
main = do
inputFile <- getArgs
let filename = if inputFile == [] then "example.txt" else inputFile !! 0
contents <- readFile filename
let result = unlines $ fmap (tabToSpace) (lines contents)
writeFile ("New_" ++ filename) result
위키독스의 점프 투 파이썬 중
a.txt라는 파일에 있는 탭을 4개의 공백으로 바꾸어 b.txt라는 파일에 저장하고 싶다면 다음과 같이 수행해야 한다.
python tabto4.py a.txt b.txt 1. 우선 다음과 같이 tabto4.py 파일을 작성해 보자.
(※ tabto4.py는 C:\Python 디렉터리에 저장한다.)
# c:/Python/tabto4.py
import sys
src = sys.argv[1]
dst = sys.argv[2]
print(src)
print(dst)
sys.argv를 이용하여 입력값을 확인하도록 만든 코드이다.
C:\Python>python tabto4.py a.txt b.txt a.txt b.txt 입력으로 전달한 a.txt와 b.txt가 정상적으로 출력되는 것을 확인할 수 있다.
Life is too short You need python 4. 이제 탭 문자를 포함한 a.txt 파일을 읽어서 탭을 공백 4개로 변환할 수 있도록 코드를 변경해 보자.
# c:/Python/tabto4.py
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
print(space_content)
위 코드는 src에 해당되는 입력 파일을 읽어서 그 내용을 tab_content라는 변수에 저장한 후 문자열의 replace 함수를 이용하여 탭(\t)을 4개의 공백으로 변경하는 코드이다.
C:\Python>python tabto4.py a.txt b.txt Life is too short You need python 아마도 탭 문자가 공백 4개로 변경되어 출력될 것이다. 하지만 탭과 공백의 차이점을 눈으로 확인할 수는 없으므로 탭이 정상적으로 공백으로 변경되었는지 확인하기 어렵다.
# c:/Python/tabto4.py
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
f = open(dst, 'w')
f.write(space_content)
f.close()
탭이 공백으로 변경된 space_content를 출력 파일인 dst에 쓰도록 코드를 수정하였다.
C:\Python>python tabto4.py a.txt b.txt 위 명령을 수행하면 b.txt 파일이 C:\Python 디렉터리에 생성된다. 에디터로 b.txt 파일을 열어서 탭이 4개의 공백 문자로 변경되었는지 확인해 보자. 프로그램 작성 시 사용하는 에디터는 대부분 탭과 공백 문자를 다르게 표시하므로 눈으로 확인이 가능할 것이다.
저작권은 박응용씨한테 있습니다.
public class TabTo4Space { public static void main(String[] args) throws IOException{
FileInputStream originalFis = null;
FileOutputStream outputFis = null;
try{
originalFis = new FileInputStream(new File("D:/temp/String.java"));
outputFis = new FileOutputStream(new File("D:/temp/StringOutput.java"));
int readValue = 0;
while((readValue = originalFis.read())!= -1){
char character = (char)readValue;
if(character =='\t'){
outputFis.write(' ');
outputFis.write(' ');
outputFis.write(' ');
outputFis.write(' ');
}else{
outputFis.write(readValue);
}
}
}catch(IOException ioe){
}finally{
if(originalFis != null){
originalFis.close();
}
if(outputFis != null){
originalFis.close();
}
}
}
}
#with 사용시 file open/close 필요 X
# " " 보다는 " " * 4가 더 가독성이 좋음
with open('output.txt',"wb") as wp:
with open("input.txt",'rb') as rp:
for line_no,line in enumerate(rp):
replaced = line.replace("\t", " " * 4)
writeline = wp.write(replaced)
파이썬 3.x 기준 변환할 파일을 입력하고, 새로 저장할 이름을 입력하여 만들었습니다.
# -*- coding: utf-8 -*-
# 파일을 읽어서 탭을 공백4개로 치환
name = input('Read file name : ')
new = input('Save file name : ')
f = open(name, 'r')
tab = f.read()
space = tab.replace("\t", " "*4)
f.close()
f = open(new, 'w')
f.write(space)
f.close()
from functools import reduce
def space4indent(address):
text=open(address, "r+")
ls=text.readlines()
result=reduce(lambda x,y: x+"".join(map(lambda x: x.replace("\t"," ",1), y)), ls)
text.close()
file=open("text.py", "w");file.write(result);file.close()
space4indent("text.py")
src=open('file.txt','r')
dst=open('dest.txt','a')
lines = src.readlines()
for line in lines:
dst.write(line.replace("\t"," "*4))
import codecs
with codecs.open('a.txt', 'r', 'utf8') as read_file:
with codecs.open('a_.txt', 'w', 'utf8') as write_file:
for row in read_file:
write_file.write(row.replace('\t', ' '))
import codecs
with codecs.open('a.txt', 'r', 'utf8') as read_file:
with codecs.open('a_.txt', 'w', 'utf8') as write_file:
for row in read_file:
write_file.write(row.replace('\t', ' '))
python : 3.5.2
answer is ...
filename = input('filename ? ')
new_filename = filename + '.new'
file = open(filename, 'r')
new_file = open(new_filename, 'w')
for i in file :
changes = i.replace('\t', ' ')
new_file.write(changes)
file.close()
new_file.close()
파이썬
inp1 = input("파일명 입력: ")
f = open(inp1)
a = f.read()
f.close()
f = open(inp1,'w')
f.write(a.replace("\t"," "))
f.close
파이썬 3.6 (replace 안쓴 풀이)
f = open("파일경로/파일이름", 'r') #파일을 불러서 엽니다.
while True: #반복문을 실행합니다.
line = f.readline() #파일에 작성된 코드를 한줄씩 문자열 형태로 읽어옵니다.
if not line: break #더이상 읽어올 줄이 없으면 반복문을 종료합니다.
snts = "" #임의의 변수에 빈 문자열을 담아둡니다.
for i in line: #읽어온 한줄을 한글자씩 확인하는데,
if i == '\t': #이때 탭(\t)이 있으면
i = '____' #띄워쓰기 4칸으로 바꿔줍니다. (눈에 더잘띄라고 _로했습니다.)
snts += i #확인(?)을 마친 한글자씩 변수에 담고,
print(snts) #한문장씩 출력합니다.
f.close() #파일을 닫습니다.
전형적인 입문자 수준의 코드입니다. 파일을 읽어와서 출력하는 프로그램입니다. 파일 열고 닫는게 미흡해서 출력하는 수준으로 했구요. replace함수 안쓰고 해보려고 노력했습니다.
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class TabConverterSpace {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File(""));
PrintWriter pw = new PrintWriter(new File(""));
while (sc.hasNext()) {
String a = sc.nextLine();
pw.println(a.replaceAll(" ", " "));
}
sc.close();
pw.close();
}
}
package training;
public class ReplaceTapToSpace {
public static void main(String[] args) {
String strSample = "Hello\tWorld";
String strResult = strSample.replaceAll("\t", " ");
System.out.println("org text : " +strSample );
System.out.println("cov text : " +strResult );
}
}
def tap_to_4space(code):
result = ""
for i in code:
if i == '\t':
result += " "
else:
result += i
return result
f = open("original.txt", 'r')
code1 = f.read()
f.close()
result1 = tap_to_4space(code1)
f = open("result.txt", 'w')
f.write(result1)
f.close()
파이썬 3.5입니다. 탭을 4개의 space로 변경하기 원하는 원본코드 파일의 내용 전체를 read()함수를 사용해서 문자열로 리턴한 다음, 그 문자열의 처음부터 끝까지 체크하면서 탭이 들어간 부분은 4개의 space로 바꿔줬습니다. 그리고 result.txt에 변환된 결과를 출력시켰습니다. 구현하고 나서 풀이해놓으신 것들을 살펴보니, replace() 함수를 사용하면 훨씬 간단하군요.^^;; 이상 파이썬 초보의 문제풀이였습니다.
f = open('file.txt', 'r')
a = f.read()
b = a.replace("/t", " ")
f = open('file.txt', 'w')
f.write(b)
f.close()
#include <stdio.h>
#include <string.h>
static FILE *_open_file(const char *ppath, const char *pmode);
static int _close_file(FILE **ppfile);
static int _change_tap_to_blank_func(FILE *pread, FILE *pwrite);
///////////////////////////////////////////////////////////////////////////////
static FILE *_open_file(const char *ppath, const char *pmode)
{
FILE *pnew = fopen(ppath, pmode);
if (pnew == NULL)
{
printf("[ERR] Fail to file open. %s %s %d\n",
__FILE__, __func__, __LINE__);
goto error;
}
error :
return pnew;
}
static int _close_file(FILE **ppfile)
{
if (ppfile == NULL)
{
printf("[ERR] File points NULL status already. %s %s %d\n",
__FILE__, __func__, __LINE__);
goto error;
}
if (*ppfile)
{
fclose(*ppfile);
*ppfile = NULL;
}
return 0;
error :
return -1;
}
static int _change_tap_to_blank_func(FILE *pread, FILE *pwrite)
{
int i;
int len;
char str[512] = {0, };
while (fgets(str, sizeof(str), pread))
{
str[strlen(str) - 1] = '\0';
len = strlen(str);
for (i = 0; i < len; i++)
{
(str[i] == '\t') ?
fprintf(pwrite, " ") :
fprintf(pwrite, "%c", str[i]);
}
fprintf(pwrite, "\n");
}
return 0;
}
int main(void)
{
FILE *pread = _open_file("tap_to_blank.c", "r");
if (pread == NULL)
goto error;
FILE *pwrite = _open_file("new_file", "w");
if (pwrite == NULL)
goto error;
_change_tap_to_blank_func(pread, pwrite);
error :
_close_file(&pwrite);
_close_file(&pread);
return 0;
}
c언어로 구현했습니다. tap_to_blank.c 파일을 읽어서 new_file로 변경하면서 탭을 공백4칸으로 변경 합니다.
python 3.4.2
import sys
old_file_name = sys.argv[1]
new_file_name = sys.argv[2]
old_file = open(old_file_name)
old_file_str = old_file.read()
old_file.close()
new_file_str = old_file_str.replace("\t", " "*4)
new_file = open(new_file_name, "w")
new_file.write(new_file_str)
new_file.close()
변환방식은 명령행 뒤에 argument 로
pi@raspberrypi:~/example $ sudo python3 tab4spaces.py eg_source.txt.py no_tab.py
pi@raspberrypi:~/example $ cat no_tab.py
tab
4spaces
tab+4spaces
tab+tab
tab+tab+4sapces
tab+tab+tab
tab*4
아래 내용을 test.py라고 저장했을 경우
cmd에서 c:>python test.py abc def 라고 입력하면 abc이 있는 탭을 모두 스페이스 4개로 바꿔서 def로 저장하도록 만든 것입니다.
# coding = utf-8
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src,"r")
tempfile = f.read()
replacefile = tempfile.replace("\t"," ")
f.close()
dst = open(dst,"w")
dst.write(replacefile)
dst.close()
어렵군요 ㅜㅜ
import java.io.*;
public class TabtoSpace{
public static void main(String[] args){
TabtoSpace ts = new TabtoSpace();
String curdir = System.getProperty("user.dir");
String filename = ts.findfile(curdir);
if(filename.equals("no"))
System.out.println();
else
ts.toSpace(filename);
}
String findfile(String filename){
File f = new File(filename);
String[] lists = f.list();
for(int i=0;i<lists.length;i++){
if(lists[i].endsWith(".java"))
return lists[i];
}
return "no";
}
void toSpace(String filename){
File f = new File(filename);
try{
FileReader reader = new FileReader(f);
FileWriter writer = new FileWriter("output.txt");
int get_asc=0;
while((get_asc=reader.read())!=-1){
char get_char = (char)get_asc;
if(get_char =='\t'){
get_char=' ';
for(int i=0;i<4;i++){
writer.write(get_char);
}
}
else{
writer.write(get_char);
}
}
writer.close();
reader.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
f = open(F, 'r')
R = open("Newtext.txt", 'w')
while True:
line = f.readline()
if not line:
break
for i in line:
if i == '\t':
line = line.replace('\t', ' ', 1)
elif i != '\t':
break
R.write(line)
f.close()
R.close()
c로 풀이.
#include <stdio.h>
int main(void)
{
int m;
FILE*fp,*fp2;
char file_name[10],new_file[10];
printf("열 파일 이름 : ");
scanf("%s",file_name);
fp=fopen(file_name,"r");
printf("작성할 파일 이름 : ");
scanf("%s",new_file);
fp2=fopen(new_file,"w");
while(!feof(fp))
{
m=fgetc(fp);
if (m==9) fprintf(fp2," ");
else fputc(m,fp2);
}
printf("%d",'\t');
fclose(fp);
fclose(fp2);
return 0;
}
public class TabReplaceSpace {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("1\t2\t3\t4\t5\n");
sb.append("1\t2\t3\t4\t5\n");
sb.append("1\t2\t3\t4\t5\n");
// (숫자 5글자 + 특수문자(탭/엔터) 5글자) * 3줄 = 30
System.out.println("길이 : " + sb.toString().length());
System.out.println(sb.toString() + "\n");
String str = sb.toString();
// str = str.replaceAll("\\t", "...."); // 이것!!!
str = str.replaceAll("\\t", " "); // 이것!!!
// (숫자 5글자 + 특수문자(엔터) 1글자 + 공백 16) * 3줄 = 66
System.out.println("길이 : " + str.length());
System.out.println(str);
}
}
import os
def change_text(filename):
f=open(filename,'r')
while True:
line=f.readline()
if not line:
break
list_line=list(line)
for i in range(len(list_line)):
if list_line[i] == "\t":
del list_line[i]
list_line.insert(i," ")
list_line="".join(list_line)
print(list_line)
f.close()
dirname="C:/test/test.txt"
change_text(dirname)
Replace를 최대한 피해서 작성했습니다. 직접 입력하는 방식이죠. C입니다.
// 탭 바꾸기 - C
#include <stdio.h>
#include <string.h>
int main(void)
{
char text[16384]; int i, j; char temp[16384];
printf("Ready>>>\n");
gets(text);
strcpy(temp, text);
for (i = 0; i < 16384; i++)
{
if (text[i] == '\t')
{
for (j = 0; j < 4; j++)
text[i + j] = ' ';
for (j = i; j < 16380; j++)
text[j + 4] = temp[j + 1];
strcpy(temp, text);
}
if (text[i] == '\0')
break;
}
puts(text);
}
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
string indent_tabTospace(const string &strLine)
{
string strTemp = strLine;
int cnt_tabs = 0;
for (int i = 0; i < strTemp.length(); i++) {
if (strTemp[i] == '\t')
cnt_tabs += 1;
else
break;
}
strTemp.erase(0, cnt_tabs);
for (int i = 0; i < cnt_tabs; i++)
strTemp.insert(0, " ");
return strTemp;
}
int main(int argc, char** argv)
{
ifstream fin;
ofstream fout;
string strTemp = "";
fin.open(argv[1]);
fout.open("output.txt");
vector<string> lineString;
while(!fin.eof())
{
getline(fin, strTemp);
lineString.push_back(strTemp);
}
for ( auto s : lineString )
{
strTemp = indent_tabTospace(s);
fout << strTemp << endl;;
}
fin.close();
fout.close();
return 0;
}
def make_str(chr, num_of_chr):
result = ''.join([' ' for i in range(num_of_chr)])
#for i in range(num_of_chr):
# result += chr
return result
def tab_to_space(code, num_of_space):
str_space = make_str(' ', num_of_space)
code = code.replace('\t', str_space)
return code
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
string indent_tabTospace(const string &strLine)
{
string strTemp = strLine;
int cnt_tabs = 0;
//for (int i = 0; i < strTemp.length(); i++) {
for (int i = 0; i < strTemp.length(); i++) {
if (strTemp[i] == '\t')
cnt_tabs += 1;
else
break;
}
strTemp.erase(0, cnt_tabs);
for (int i = 0; i < cnt_tabs; i++)
strTemp.insert(0, " ");
return strTemp;
}
int main(int argc, char** argv)
{
ifstream fin;
ofstream fout;
string strTemp = "";
fin.open(argv[1]);
fout.open("output.txt");
vector<string> lineString;
while(!fin.eof())
{
getline(fin, strTemp);
lineString.push_back(strTemp);
}
for ( auto s : lineString )
{
strTemp = indent_tabTospace(s);
fout << strTemp << endl;;
}
fin.close();
fout.close();
return 0;
}
정규식
import re
def noop():
def noop2():
pass
def noop3():
def noop4():
if True:
pass
else:
pass
pass
me = open(__file__).read()
print(re.sub(r'^\t+', lambda m: '....'*len(m.group()), me, flags=re.MULTILINE))
그냥
def tab_to_space(srcfile):
code = []
with open(srcfile, 'r') as f:
while True:
line = f.readline()
if not line:
break
tabcnt = 0
for char in line:
if char == '\t':
tabcnt += 1
else:
break
code.append(' ' * tabcnt + line[tabcnt:])
return ''.join(code)
JAVA입니다.
public class Ex011 {
static char[] str = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
//소스코드 입력
getInputData();
//작업 및 출력
tab2space();
System.out.println();
System.out.print("결과: ");
System.out.println(str);
}
//탭문자 -> 공백문자
static private void tab2space() {
for(int i = 0; i < str.length; i++) {
//탐색 중 탭문자가 나온다면 배열늘리고 탭문자->공백문자
if(str[i] == '\t') {
//배열 늘리고
str = spanArray(i);
//공백문자로 대체
str[i] = ' ';
str[i+1] = ' ';
str[i+2] = ' ';
str[i+3] = ' ';
System.out.print("공백문자대체후 : ");
System.out.println(str);
}
}
}
//배열 크기 늘리고 공백문자 들어갈 자리 비워두기(+3)
static private char[] spanArray(int repIdx) {
char[] span = new char[str.length+3];
int curIdx = 0;
for(int i=0; i < str.length; i++,curIdx++) {
span[curIdx] = str[i];
//탭이 발견된 위치에 도달하면 공백문자 들어갈 공간만큼 비운다.
if(i == repIdx)
curIdx+=3;
}
System.out.println();
System.out.print("배열확장및공간만듦: ");
System.out.println(str);
return span;
}
//소스코드(문자열) 입력
static private void getInputData() {
Scanner scan = new Scanner(System.in);
System.out.print("소스코드입력~: ");
String input = scan.nextLine();
str = input.toCharArray();
}
}
String 이나 StringBuffer,StringBuilder 이용하지 않고 배열로 구현해보았습니다.
입력값에는 공백문자는 없으며 탭문자를 두번 넣었습니다. <결과> 소스코드입력~: abc def ghi
배열확장및공간만듦: abc def ghi 공백문자대체후 : abc def ghi
배열확장및공간만듦: abc def ghi 공백문자대체후 : abc def ghi
결과: abc def ghi
python 3.6을 이용했습니다.
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
f = open(dst,'w')
f.write(space_content)
f.close()
위 스크립트를 통해 dos창에서 원본 txt파일을 불러오고, tab을 4개의 space로 바꾼 후 다른 txt로 저장할 수 있습니다.
package java_tutorial;
import java.util.Scanner;
public class ReplaceTab {
public static void main(String[] args) {
Scanner obj=new Scanner(System.in);
System.out.print("Input:");
String str=obj.nextLine();
System.out.println("Before:"+str);
str=str.replaceAll("\t", " ");
System.out.println("After:"+str);
str=str.replaceAll(" ", "\t");
System.out.println("Final:"+str);
}
}
[Python 3.6]
import re
def replace4space(inStr):
lines = inStr.split("\n")
for line in lines:
mat = re.match("^\t+", line)
if mat:
line = " "*mat.end() + line[mat.end():]
print(line)
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException{
FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt");
int ch;
while((ch = reader.read()) != -1) {
if(ch == '\t') writer.write(" ");
else writer.write((char) ch);
}
reader.close();
writer.close();
}
}
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
f = open(dst,'w')
f.write(space_content)
f.close()
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
String replacedText = null;
if (input.contains("\t")) {
replacedText = input.replace("\t", " ");
}
System.out.println(replacedText);
br.close();
}
}
public class Question_019 {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("d:\\Person\\study\\workspace\\codingDojang\\src\\codingDojang\\Question_019.java");
FileWriter fw = new FileWriter("d:\\Person\\study\\workspace\\codingDojang\\src\\codingDojang\\Question_019.txt");
int data = 0;
while((data = fr.read()) != -1) {
if((char)data == 9) {
data = (byte)32;
for(int i = 0; i < 4; i++) {
fw.write(data);
}
} else {
fw.write(data);
}
}
fr.close();
fw.close();
}
}
public class Example19 {
public static void main(String[] args) {
String str = "들여쓰기 테스트";
StringBuilder sb = new StringBuilder();
sb.append(str.replaceAll("\t", " "));
System.out.println(sb.toString());
}
}
replaceAll 이용해서 간단하게 작성해 보았습니다.
import os
def f(dir1):
for (path, dir, files) in os.walk(dir1):
for filename in files:
if filename.split('.')[-1] == 'py':
f1 = open(os.path.join(path, filename))
f2 = f1.read().replace('\t',' ')
f1.close()
f1 = open(os.path.join(path, filename),'w+')
f1.write(f2)
f1.close()
f('D:\\')
with open('name.in') as fin: #파일을 연다
while True:
rline=fin.readline() #읽는다
if not rline : break #만일 읽은게 없으면 파일 끝으로 간주하고 탈주
if rline[0] == '\t' : rline=' '+rline[1:] #첫 문자가 탭이면 4공백으로 교환
print rline #출력
public class tab_to_space {
public static void main(String[] args) {
String str="aaa\taaa\taaa";
System.out.println(str);
str=str.replaceAll("\t"," ");
System.out.println(str);
}
}
package codingdojang;
public class ex19 {
public static String change(String a) {
String b = a.replaceAll("\t"," ");
return b;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "a b c d";
System.out.println(change(a));
}
}
def transformation(filename, newname): #전자는 기존 파일, 후자는 새로 쓸 파일이름
a = open(filename, 'r').read() # 문자열로 만듦
a = a.replace('\t', ' ' * 4)
with open(newname, 'w') as f:
f.write(a)
int main()
{
char str[] = { "abcd\ttefgh\tijkl\n" };
int i;
printf("%s", str);
for (i = 0; i < sizeof(str) / sizeof(char); i++);
{
if (str[i] == '\t')
{
str[i] = ' ';
}
}
printf("%s \n", str);
getchar();
return 0;
}
}
def Tab_to_Space(Centense): Centense.replace("\t"," ") print(Centense)
Tab_to_Space("adwfhhadshf\tddafdijsl")
txt에 한줄 만들어서 확인했을땐 작동은 했습니다..
code1 = open('파일경로\파일이름','r')
data1 = code1.read()
data2 = data1.replace('\t',' ')
code2 = open('파일경로\파일이름2','w')
code2.write(data2)
code2.close()
import sys
inf = open(sys.argv[1], 'r')
tem = inf.read()
inf.close()
inf = open(sys.argv[1], 'w')
inf.write(tem.replace("\t"," "*4))
inf.close()
f = open('Tab_to_Space4_1.txt','r')
h = open('Tab_to_Space4_2.txt','w')
a=f.read().replace(' ',' ')
h.write(a)
h.close()
f.close()
fin=open("test.txt",'r')
fout=open("test2.txt",'w')
allline = fin.read()
allline2 = allline.replace("\t"," "*4)
fout.write(allline2)
fin.close()
fout.close()
public class Tab {
public static void main(String[] args) {
Scanner obj=new Scanner(System.in);
System.out.print("Input:");
String str=obj.nextLine();
System.out.println("Before:"+str);
str=str.replaceAll("\t", " ");
System.out.println("After:"+str);
str=str.replaceAll(" ", "\t");
System.out.println("Final:"+str);
}
}
import os
print("<<< Convert tab to 4 spaces>>>","\n")
srfile = input("Enter the file name(usage : name.ext):") # 소스파일 이름을 입력받음
dir = os.getcwd() # 프로그램을 실행하는 현재폴더 위치를 리턴받음
def search(dir):
filenames = os.listdir(dir) # 현재폴더의 파일 또는 디렉토리 이름들을 리스트로 리턴받음
for filename in filenames:
full_filename = os.path.join(dir, filename) # 현재폴더와 파일명(또는 디렉토리)이름을 결합하여 리턴받음
if os.path.isdir(full_filename): # 결합하여 리턴받은 값이 디렉토리이면
search(full_filename) # 디렉토리이면 해당 디렉토리의 파일 또는 디렉토리 이름들을 리스트로 리턴받음(하위폴더 검색)
if filename == srfile:
f = open(full_filename, 'r')
source = f.read() # 파일의 내용을 읽어들여
converted = source.replace("\t"," "*4) # 'tab' 문자를 '공백 4개'로 변환한 내용을 coverted 객체로 리턴함
f.close()
f = open("new_"+srfile, 'w') # 변환된 내용을 저장할 새로운 파일을 열고
f.write(converted) # converted 객체의 변환된 내용을 새로운 파일에 저장함
f.close()
print("\n")
print("Process complete!")
print("'%s' file created." % ("new_"+srfile))
input(" ")
break #프로세스를 종료함
search(dir)
tmp=''
with open('test', 'r') as fr:
for line in fr:
line=line.replace('\t',' '*4)
tmp+=line
with open('test', 'w') as fw:
print(tmp, file=fw)
test파일 내용은
tab3
tab2
tab1
tab0
입니다.
#!/usr/bin/python
import getopt
import sys
import os
def check(path):
if path == "False":
print("The directory does not exist in the path.")
else:
print("A directory exists in the path.")
def rep_line(get_line):
rep_line=get_line.replace('\t', ' * ')
return(rep_line)
def print_help():
return ("""
Please enter the following options
==================================
-r: Convert tabs to 4 spaces.
Please enter a Text filename to convert.
==================================
-h: View the help message again.
""")
def main():
try:
opts, args=getopt.getopt(sys.argv[1:], "r:")
except getopt.GetoptError as err:
print str(err)
sys.exit(1)
for opt, arg in opts:
if opt == "-r":
path=(sys.argv[2])
check(path)
file=open(path, 'r')
for line in file.readlines():
result=rep_line(line)
print result
wfile=open(path+'.new', 'a')
wfile.write(result)
elif opt == "-h":
print_help()
if __name__ == '__main__':
main()
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class Main {
public static void main(String[] args) throws Exception {
//파일을 입출력
BufferedReader br = new BufferedReader(new FileReader("C:/Users/Lee/Documents/tab.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("C:/Users/Lee/Documents/output.txt"));
//파일 내용을 제일 윗줄 부터 한줄씩 읽어서 마지막 까지 loop
while (true) {
//파일에 내용을 한줄씩 String에 저장
String line = br.readLine();
//파일에 끝에 도달하면 loop 종료
if (line == null)
break;
//String 안에 탭문자(\t)를 " "으로 변환
line = line.replaceAll("\t", " ");
//출력 시킬 파일에 기록
bw.write(line);
//개행 문자 삽입
bw.newLine();
}
//사용한 파일입출력 종료
br.close();
bw.close();
}
}
li = 'hi hello \n hi hello\n hi'
li = list(li)
find =['32','32','32','32']
lis=[]
liss=[]
x = 0
y = 1
for i in li:
l = ord(i)
lis.append(l)
for _ in lis:
if lis[x] == 10:
x = x+1
if lis[x] == 9:
lis[x] = find
continue
x = x + 1
print(lis)
basestring = (str,bytes)
test =''
ping =[]
ping2 =[]
def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
#스트링형이 아닌 이터러블의 경우 - 재귀한 후, extend
result.extend(flatten(el)) #재귀 호출
else:
#이터러블이 아니거나 스트링인 경우 - 그냥 append
result.append(el)
return result
lis = flatten(lis)
for i in lis:
test = int(i)
ping.append(test)
for i in ping:
test = chr(i)
ping2.append(test)
print(ping2)
s = ''.join(ping2)
print(s)
public class tab_to_space {
public static void main(String[] args) {
String sampleString = "tabsldfjlrwTabsdflkjsfdlfTabsldkjf";
System.out.println("이전"+sampleString);
sampleString = sampleString.replaceAll("Tab", " ");
System.out.println("결과 : "+sampleString);
}
}
문자 Tab 이라길래 \t을 칠수 없는 상황이 문제인건가 했는데 다른 분들 소스 보니 아닌가보네요 Tab->\t로 바꾸면 될 듯 합니다.
filename = input("파일 이름을 입력하십시오: ")
with open(filename, "r") as f:
Text = f.readlines()
for i in range(len(Text)):
exchangedText= Text[i].replace("/t"," ")
with open(filename+"_exchanged", "w") as h:
h.write(exchangedText)
import java.util.Scanner;
public class tab {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String space = line.replaceAll("\t", " ");
System.out.println(space);
}
}
import sys
Init = sys.argv[1]
f = open(Init, 'r')
tab = f.read()
space = tab.replace('\t', ' ')
with open(Init, 'w') as g:
g.write(space)
이렇게 해봤더니 문제점: 한글이 깨집니다. 글자인코딩에 대해서는 잘 몰라서 해결은 못했습니다...
파이썬 입니다.
def to4space(src):
result=""
result=src.replace('\t',' ')
return result
print(to4space('''
sum=0
for i in range(1,1000):
if i%3==0 or i%5==0:
sum=sum+i
else:
continue
print(sum)
'''))
#renderer.py
import sys
original = sys.argv[1]
edited = sys.argv[2]
f = open(original)
tab_content=f.read()
f.close()
space_content = tab_content.replace("\t"," "*4)
print(space_content)
실행 시 ..../render.py a.txt b.txt
code = 'this sentence has\ttab in the middle.'
print(code)
def tab2space(code):
code_split = code.split('\t')
code_join = ' '.join(code_split)
return code_join
print(tab2space(code))
#include <stdio.h>
int main(void){
int i;
char testch[] = "this\tis the\ttest sentence!";
printf("[%s]\n", testch);
for(i=0;i<sizeof(testch);i++){
if(testch[i]=='\t'){
testch[i]=' ';
}
}
printf("[%s]\n", testch);
return 0;
}
자바입니다
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
List<String> list = new ArrayList<String>();
while(true) {
System.out.print("코드(종료시 입력하지 않고 Enter) = ");
String read = cin.nextLine();
if(read.length() == 0) {
for(String str : list) {
System.out.println(str);
}
break;
}else {
list.add(replace(read));
}
}
cin.close();
}
public static String replace(String data) {
return data.replaceAll("\t", " ");
}
import sys
tab = sys.argv[1]
space = sys.argv[2]
f = open(tab)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
f = open(space, 'w')
f.write(space_content)
f.close()
filename = input("파일 이름 입력: ")
readfile = open(filename, 'r')
writefile = open('outfile.txt', 'w')
contents = readfile.read()
replaced_contents = contents.replace('\t', ' ')
writefile.write(replaced_contents)
readfile.close()
writefile.close()
static void Main(string[] args)
{
Console.Write("TAB을 포함한 소스코드 입력:");
string strTabCode = Console.ReadLine();
Console.WriteLine(strTabCode.Replace("\t", " "));
}
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
f = open(dst, 'w')
f.write(space_content)
f.close()
filename=input("Enter your file name : ") tempfile=open(filename) tempfile=tempfile.read() temp_str=tempfile.replace("\t"," ") tempfile=open(filename,'w') tempfile.write(temp_str) tempfile.close()
# 파이썬
# tab_to_space.py
# command line: python tab_to_space.py space_file.txt tab_file.txt
import sys
a1 = sys.argv[1]
a2 = sys.argv[2]
f = open(a1)
tabs = f.read()
f.close()
spaces = tabs.replace("/t", " "*4)
f = open(a2, 'w')
f.write(spaces)
f.close
import re
sourcecode = '''A씨가 납품하려는 소스코드
sdasdasdw
asdasdasd
asdsdsd'''
p = re.compile('^\t', re.MULTILINE)
sourcecode = p.sub(' '*4, sourcecode)
sourcecode
java 8
String input = "abc bbb ddd";
String result = "";
for(int i=0; i<input.length(); i++) {
char ch = input.charAt(i);
if(ch == '\t') {
result = result + " ";
}else {
result = result + Character.toString(ch);
}
}
System.out.println("result >> " + result);
file_path=input("변경하고자 하는 파일의 경로를 입력하시오.ex)\"C:\Python\\test.txt\"\n")
f=open(file_path,'r')
content=f.read()
changed_content=content.replace('\t',' '*2)
f.close()
f=open(r"C:\Users\BOOKER\result.txt",'w')
f.write(changed_content)
f.close
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream in;
ofstream out;
string tmp;
in.open("Original.txt");
out.open("Fixed.txt");
while (!in.eof())
{
getline(in, tmp);
if (tmp[0] == '\t')
{
tmp.erase(0, 1);
tmp.insert(0, " ");
}
out << tmp << endl;
tmp.clear();
}
in.close();
out.close();
return 0;
}
txt파일을 읽어서 변환하고 저장하는 프로그램입니다! 자바입니다!
package CodingDojang;
import java.util.regex.*;
import java.util.*;
import java.io.*;
class TabConverter {
private static String tabConverter(String _input) {
String output;
output = _input.replaceAll("\t", " ");
return output;
}
public static void main(String[] args) {
String temp;
File readFile = new File("C:\\Users\\sangw\\Desktop\\상우\\프로그래밍\\코딩도장", "test.txt");
File writeFile = new File("C:\\Users\\sangw\\Desktop\\상우\\프로그래밍\\코딩도장", "testConverted.txt");
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(readFile));
bw = new BufferedWriter(new FileWriter(writeFile));
String line;
while ((line = br.readLine()) != null) {
temp = tabConverter(line);
bw.write(temp);
bw.newLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(br != null && br != null) try {br.close(); bw.close();} catch (IOException e) {}
}
}
}
import os
# 1-1파일 위치와 확장자 입력 받기
filepath = input("파일경로를 입력하세요: ")
ext = input("확장자를 입력하세요: ")
'''
2 파일 전체경로 리스트로 받기
파일경로와 확장자를 파라메터로 받아서 하위디렉토리 모두 탐색해서 조건에
맞는 파일전체경로를 list 에 담아 리턴한다.'''
# 1-2 함수: 변수 - 파일 경로, 확장자를 받으면 - 파일경로를 리스트로 저장
def getfilelist(filepath, ext):
filelist = []
for path, dir, files in os.walk(filepath):
for filemn in files:
if (filemn.lower()).endswith(ext.lower()):
filelist.append(path + "\\" + filemn)
return filelist
# 2-1 :파일경로 및 확장자를 받아서 출력, 백업파일 생성 (copy 경로 파일경로.bak)
for _path in getfilelist(filepath,ext):
print(_path)
os.system("copy %s %s" % (_path, _path + ".bak"))
# 2-2 : 백업파일을 열고 읽은다음, 새로운 변수에 저장, replace 하기
with open(_path + ".bak", 'r') as f:
srcContent = f.read()
with open(_path, 'w') as tempo:
tempo.write(srcContent.replace("\t"," "))
무명소졸님의 코드를 보고 공부했습니다.
package Q1;
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;
public class Q19 { public static void main(String[] args) { File inFile = new File("C:\Users\Public", "in.txt"); File outFile = new File("C:\Users\Public", "out.txt"); String before,stop=""; try { BufferedReader br = new BufferedReader(new FileReader(inFile)); BufferedWriter bw = new BufferedWriter(new FileWriter(outFile));
while ((before = br.readLine()) != null) {
System.out.println(before);
stop = before.replace("\t", " ");
bw.write(stop);
bw.newLine();
}
bw.flush();
br.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PracticeWW
{
class Replace
{
public string Change()
{
string nameChange = name.Replace("\t", " ");
return nameChange;
}
public static string name = "\t홍\t길\t동";
}
class Program
{
static void Main(string[] args)
{
Replace replace = new Replace();
Console.WriteLine(Replace.name);
Console.WriteLine(replace.Change());
}
}
}
C#입니다
Of = input("ENTER FILE NAME: ")
Of= open(Of)
data = Of.read()
data = data.replace('\t',' ')
Nf = open("Newfile.txt",'w')
Nf.write(data)
Of.close()
Nf.close()
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TabReplace {
public static void main(String[] args) {
// TODO Auto-generated method stub
String filePath = "C:\\Users\\present\\Desktop\\test\\1234.txt";
String filePath2 = "C:\\Users\\present\\Desktop\\test\\12343.txt";
try {
FileReader fis = new FileReader(new File(filePath));
FileWriter fos = new FileWriter(new File(filePath2));
int i=0;
while((i=fis.read()) != -1){
if(i == ' '){
fos.write(' ');
fos.write(' ');
fos.write(' ');
fos.write(' ');
}else{
fos.write(i);
}
}
fos.flush();
fis.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
file_name=input("Enter the file name :" ) fp = open("D:/{}".format(file_name,'w')) data = fp.read() date = data.replace("\t"," ") nfp = open("D:/new_{}".format(file_name),'w') nfp.write(data) fp.close() nfp.close()
import sys
fname = input("input file name :")
f = open(fname, "r")
line = f.read()
trans = line.replace("\t", " ")
f = open(fname, "w")
f.write(trans)
f.close()
python 3.6.1
filename = input("Enter the file location and name:")
file = open(filename, 'r')
file_correction = file.read().replace('\t', ' ')
fout = open(filename, 'w')
fout.write(file_correction)
file.close()
public static String tabTo4Space(String iStr) {
String oStr = "";
char[] charArr = iStr.toCharArray();
for(int i = 0; i < charArr.length; i++) {
if(charArr[i] == '\t') oStr += " ";
else oStr += charArr[i];
}
return oStr;
}
imports:
import (
"os"
"strings"
)
function:
func Tab2Spaces(filename string) {
ifile, _ := os.Open(filename)
defer ifile.Close()
stat, _ := ifile.Stat()
bs := make([]byte, stat.Size())
ifile.Read(bs)
str := string(bs)
newstr := strings.Replace(str, "\t", " ", -1)
ofile, _ := os.Create(filename + "-tab2spaced.txt")
defer ofile.Close()
ofile.WriteString(newstr)
}
import sys
src = sys.argv[1] dst = sys.argv[2]
f = open(src, 'r') tap_read = f.read() f.close()
space_contents = tap_read.replace('\t', ' '*4) f = open(dst, 'w') f.write(space_contents) f.close()
source = input()
f = open(source, 'r')
a = f.read()
p = a.replace("\t", " ")
f.close()
f = open(source, 'w')
f.write(p)
f.close()
package prob_01;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FindContent {
private static BufferedReader f_Reader;
private static BufferedWriter f_Writer;
public static void main(String[] args) throws IOException {
f_Reader = new BufferedReader(new FileReader("input.txt"));
f_Writer = new BufferedWriter(new FileWriter("output.txt"));
while(true) {
String i_dataLine = f_Reader.readLine();
StringBuffer o_data = new StringBuffer();
if(i_dataLine==null)
break;
for(int i=0; i<i_dataLine.length(); i++) {
if(i_dataLine.charAt(i)=='\t') {
o_data.append(" ");
}
else {
o_data.append(i_dataLine.charAt(i));
}
}
f_Writer.write(o_data.substring(0, o_data.length()));
f_Writer.newLine();
}
f_Reader.close();
f_Writer.close();
}
}
s = " dlafkalfkalf aldkalfalfkalkflaf aflafkalf" \ "aflaflafla aflafkalfka"
print(s.replace('\t',' '))```{.python}
```
# python3
with open('test.txt','r') as f: r = f.read()
with open('test.txt','w') as f: f.write(r.replace('\t',' '*4))
import java.util.Scanner;
public class Tab {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
str.replaceAll("\t", " ");
System.out.println(str);
}
}
#include <iostream>
using namespace std;
int main(void)
{
char cText[] = "Hello\tWorld";
cout << "바꾸기 전 문장:" << cText << endl;
cout << "변경 후 문장: ";
for (int i = 0; i < sizeof(cText); i++)
{
if (cText[i] == '\t')
cout << ' ';
else
cout << cText[i];
}
cout << endl;
}
Python 2.7
def changetabs(sourceCode):
result = str()
with open(sourceCode, 'r') as f:
lines = f.readlines()
for line in lines:
if line.startwith('\t'):
result += line.expandtabs(4)
else:
result += line
with open(sourceCode, 'w') as f:
f.write(result)
i1 = input("소스 코드 위치를 입력하세요: ") file = open(i1,'r') contents = file.readlines() for line in contents: line = line.replace('\t',' ') file.close() file = open(i1,'w') file.write(contents)
// 자바입니다
public static void main(String[] args) {
String str="aaa\taaa\taaa";
str=str.replaceAll("\t"," ");
System.out.println(str);
}
// 스트링 메서드 좋은 게 많네요
자바 내장함수 replaceAll 사용했습니다.
public class T {
public static void main(String[] args) {
String str="aaa\taaa\taaa";
System.out.println(str);
str=str.replaceAll("\t"," ");
System.out.println(str);
}
}
/*
탭을 공백 문자로 바꾸기
A씨는 개발된 소스코드를 특정업체에 납품하려고 한다. 개발된 소스코드들은 탭으로 들여쓰기가 된것,
공백으로 들여쓰기가 된 것들이 섞여 있다고 한다. A씨는 탭으로 들여쓰기가 된 모든 소스를 공백 4개로 수정한 후 납품할 예정이다.
문제
A씨를 도와줄 수 있도록 소스코드 내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램을 작성하시오.
*/
package codingTest;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReTaWithSpCh {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); // 텍스트 파일 읽어오는 스캐너
String fileroute = "./src/codingTest/Text/replaceAllTest.txt"; // 소스파일 텍스트로 복사해서 소스 수정
String text;
boolean flag = true; // 불분명문자 판별 플래그
try {
scan = new Scanner(new File(fileroute));
while(scan.hasNextLine()) {
if(flag) { text = scan.nextLine().substring(1); flag = false; } // 윈도우에서 쓴 글이므로 첫줄 가장첫문자에 불명문자 빼고 가져옴.
else { text = scan.nextLine(); flag = true; }
System.out.println(text + " <- 바꾸기전 문자열(소스)");
}
System.out.println("");
scan = new Scanner(new File(fileroute));
while(scan.hasNextLine()) { // 읽어올 줄 있나판별
if(flag) { text = scan.nextLine().substring(1); flag = false; }
else { text = scan.nextLine(); }
text = text.replaceAll("\t", " ");
System.out.println( text + " <- 바꾼 후 문자열(소스)");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
def fileTap2Space(fname):
with open(fname, 'r', encoding="UTF8") as f:
data = f.read()
data = data.replace("\t", " " * 4)
with open(fname, 'w', encoding="UTF8") as f:
f.write(data)
return data
#print(fileTap2Space('1. Multiples of 3 and 5.py'))
import os
#_dir = input("_dir: ")
#ext = input("ext: ")
_dir = 'C:\\Users\\Administrator\\PycharmProjects'
ext = '.py'
for root, dirs, files in os.walk(_dir):
for file in files:
if file.endswith(ext):
print(fileTap2Space(root + '\\' + file))
public class TabToSpace {
public static void main(String[] args) {
// TODO Auto-generated method stub
String sentence = "hi \t\t\t\t\tt\t\t my name is jun";
System.out.println(sentence);
System.out.println(sentence.replace("\t", " "));
}
}
#! Python
import os
def encodingFile(fileName):
f = open(fileName, 'r')
fi = open(fileName, 'w')
for data in f.read():
data.replace("\t", " "*4)
fi.write(data)
f.close()
fi.close()
encodingFile("test.py")
f = open(filename, 'r')
data = f.read()
data = data.replace("\t", " ")
f_new = open(filename_new, 'w')
f_new.write(data)
f_new.close()
f.close()
fr = open("test", 'r')
fw = open("test2", 'w')
while True:
line = fr.readline()
if not line:
break;
for i in range(0, len(line)):
if line[i] == '\t':
fw.write(' ' * 5)
else :
fw.write(line[i])
fr.close()
fw.close()
with open('SourceCode.txt', 'r') as f:
new = (f.read()).replace('\t', ' ')
with open('SourceCode.txt', 'w') as f:
f.write(new)
static void Main(string[] args) { string Text = File.ReadAllText(@"E:\TebTest.txt"); Text = Text.Replace('\t', ' '); Text = Text.Replace(" ", " ");
Console.WriteLine(Text);
}
import sys, os
f = open( sys.argv[1], 'r' )
t0 = f.read()
f.close()
f = open( sys.argv[1], 'w' )
f.write( t0.replace( '\t', ' ' * 4 ) )
f.close()
os.system( 'cat ' + sys.argv[1] )
한번따라해봤는데 재밌네요
f = open('test.txt','r')
s = f.read().replace('\t',' ')
f.close()
f = open('test.txt','w')
f.write(s)
f.close()
쌩초보. 눈에 거슬리는거 있으면 지적좀. 없겠지만....
들여쓰기의 탭만 수정되게 하였습니다. 탭과 공백4개만을 들여쓰기로 판단합니다
text = "\t \tsource\tcode exam\tple\n"
def tabconv(text):
textsplit = text.split('\t')
i = 0
for t in textsplit: # 들여쓰기 카운트
if t == '' or t == ' ': i += 1
else : break
j = 0
result = ''
for t in textsplit:
if j < i: # 들여쓰기
result = result+t+' '
elif j == len(textsplit)-1: # 문자열 마지막 부분
result = result+t
else: # 문자열
result = result+t+'\t'
j = j+1
return result
with open('d:/temp/ex.txt','w',encoding='utf8') as f:
print('원본: '+text,file=f,end='')
print('수정: '+tabconv(text),file=f,end='')
package com.company;
import java.io.*;
public class Changetext {
public static void fileReader(String filename) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filename));
BufferedWriter wr = new BufferedWriter(new FileWriter("test1.txt"));
String line;
try {
while ((line = br.readLine()) != null) {
String li = line.replaceAll("\t", " ");
wr.append(li + "\r\n");
System.out.println(line.equals(li));
}
}
catch (FileNotFoundException e){
System.err.println("파일이없습니다");
}
catch (IOException e){
System.err.println("무슨이유로 처리할수없습니다.");
}
finally {
br.close();
wr.close();
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
Changetext.fileReader("test.txt");
}
}
with open('C:\\Park\\file.txt','r') as file:
text=file.read()
replaced_text=text.replace('\t',' ')
with open('C:\\Park\\replaced_file.txt','w') as replaced_file:
replaced_file.write(replaced_text)
package kennsyu_イスンウ_個人練習;
public class cd_0003 {
public static String tapTo4Space(String source) {
String convertSource = source.replace("\t", " ");
return convertSource;
}
}
fname = input("파일 이름을 입력하세요. : ")
try:
f=open(fname,'r')
except:
print("파일 이름을 잘못입력하셨습니다. 프로그램을 종료합니다.")
quit()
flines=f.read()
f.close()
flines=flines.replace("\t",' '*4)
f1=open("tab_ex2.txt",'w')
f1.write(flines)
f1.close()
filename = input("Enter your filename: ")
f = open(filename)
print("".join(f.readlines()).replace("\t"," "))
f.close()
def fileTap2Space(fname): with open(fname, 'r', encoding="UTF8") as f: data = f.read() data.replac('\t', 'space') with open(fname, 'w', encoding="UTF8") as f: f.write(data) return data
_dir = 'C:\Users\This PC\CodingDojang' ext = '.py' for root, dirs, files in os.walk(_dir): for file in files: if file.endswith(ext): print(fileTap2Space(root + '\' + file))
using System;
using System.IO;
namespace CD019
{
class Program
{
static void Main(string[] args)
{
try
{
string filename = @"c:\temp\source.txt";
string convString = TAB2SPACE(File.ReadAllText(filename));
File.WriteAllText(filename + ".converted.txt", convString);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Environment.Exit(0);
}
}
static string TAB2SPACE(string aString) => aString.Replace("\t", " ");
}
}
b=input('파일 이름을 입력하시오:')
f=open(b)
a=f.read()
c=a.replace('n',' ')
f=open(b,'w')
f.write(c)
f.close()
str1 = raw_input("input file : ")
f = open(str1,'r')
text=f.read()
print(text)
text2=text.replace("\t"," "*4)
f.close()
var myFindChangeFile = File.openDialog('File Select');
var Finddoc = myFindChangeFile.open();
var str = Finddoc.read();
Finddoc.close();
var myResult = str.replace (/\t/g, '');
myFindChangeFile.open('w');
myFindChangeFile.write(myResult);
myFindChangeFile.close();
filename = input("파일의 이름을 입력하세요 : ") file = open(filename) file = file.read() refile = file.replace("\t", " ") file = open(filename, 'w') file.write(refile) file.close()
f = open("test.txt", 'r')
strVal = f.read()
strVal.replace("\t", " ")
f.close()
f = open("test.txt", 'w')
f.write(strVal)
f.close()
// =====================================
private static String tapToSpace(String st) {
return st.replaceAll(" ", " ");
}
import os
def replace_str(src=''):
if not src:
return src
else:
result = ''
for idx, ch in enumerate(src):
if src[idx] == '\t':
result = result + ' '
next_idx = idx + 1
if next_idx < len(src) and src[next_idx] != '\t':
result = result + src[next_idx:]
break
else:
result = result + src[idx]
return result
if __name__ == "__main__":
source = os.path.join(os.getcwd(), 'Replace', 'sample.py')
target = os.path.join(os.getcwd(), 'Replace', 'sample_new.py')
with open(source, 'r') as f:
with open(target, 'w') as f2:
for i, line in enumerate(f):
result = replace_str(line)
print "%3d : %s" %(i, result)
f2.write(result)
f2.close()
Replace라는 폴더에 sample.py라는 들여쓰기 부분에 탭이 쓰인 파일을 변경해서 sample_new.py로 저장합니다. replace함수를 쓰지 않았고 들여쓰기 부분만 변경하도록 했습니다.
public static void main(String[] args) {
StringBuilder str = new StringBuilder();
str.append("안녕\t안녕");
for(int i=0;i<str.length();i++) {
if(str.charAt(i)=='\t') {
str.insert(i+1," ");
str.deleteCharAt(i);
}
}
}
#탭을 공백 문자로 바꾸기
f = open("cord.txt", 'r') #탭으로 입력된 소스코드 파일 열기
text = f.read()
f.close()
text = text.replace('\t', ' '*4) #탭을 공백으로 바꿔주기
f = open('cord_correct.txt', 'w') #수정된 소스코드 파일 저장
f.write(text)
f.close()
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Solv {
public static void main(String[] args) {
FileReader fr;
FileWriter fw;
BufferedReader br = null;
BufferedWriter bw = null;
try {
fr = new FileReader("src.txt");
fw = new FileWriter("out.txt");
br = new BufferedReader(fr);
bw = new BufferedWriter(fw);
String line = "";
while ((line = br.readLine()) != null) {
fw.write(line.replaceAll("\t", " ") + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
JAVA 사용하여 풀이하습니다. 콘솔로 출력시 결과를 확인할 수 있습니다.
public class TapSpacebar {
public static void main(String [] args) {
String str = "abc\tabc\tabc";
System.out.println(str);
String result = TapSpacebar.replace(str);
System.out.println(result);
}
public static String replace(String str) {
String result = str.replaceAll("\t", " ");
return result;
}
}
f = open("tap.txt", "r")
lines = f.readlines()
new_lines = []
for line in lines:
if line[0] == "\t":
new_lines.append(" " + line[1:])
else:
new_lines.append(line)
f = open("modified_tap.txt", "w")
for line in new_lines:
#f.write(line + "\n") 저절로 줄바꿈 됨
f.write(line)
f.close()
char replaceAll(char s, const char olds, const char news);
void main(void){ char s[] = "/t봉숭아 /t학당! 봉숭아 학당! 봉숭아 학당! 봉숭아 학당!"; char *s2;
printf("원본: %s\n", s);
s2 = replaceAll(s, "/t", " ");
// 에러가 있으면 NULL 을 리턴. 에러가 없으면 결과 출력 (s2 != NULL) ? printf("치환: %s\n", s2) : fputs("Replace String Error...\n", stderr); }
char replaceAll(char s, const char olds, const char news) { char result, sr; size_t i, count = 0; size_t oldlen = strlen(olds); if (oldlen < 1) return s; size_t newlen = strlen(news);
if (newlen != oldlen) { for (i = 0; s[i] != '\0';) { if (memcmp(&s[i], olds, oldlen) == 0) {count++; i += oldlen;} else i++; } } else i = strlen(s);
result = (char *) malloc(i + 1 + count * (newlen - oldlen)); //이 부분은 제가 계산을 해봤는데 아마 한글때문에 이렇게계산 하신거 같은데 저도 이부분은 잘 모르겠네요 if (result == NULL) return NULL;
sr = result; // 여기는 동적할당 하고나서 result를 그대로 못써서 다른 포인터 변수에다가 대체 했습니다. 참고하시면됩니당 while (s) { if (memcmp(s, olds, oldlen) == 0) { memcpy(sr, news, newlen); sr += newlen; s += oldlen; } else sr++ = s++; } sr = '\0';
return result; }
replaceAll은 다른분 코드 신데 C로 치환이 어려워서 한번쯤 보시고 습득하시면 좋을듯요
# python 3.7.1
with open(file_path) as f:
test = f.read()
with open(file_path, 'w') as f:
f.write(" ".join(test.split("\t")))
public static void main(String[] args) {
File inputFile = new File("/Users/bellossimo/Downloads/test.txt");
File outFile = new File("/Users/bellossimo/Downloads/test_out.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
int character = 0;
while((character = reader.read()) != -1) {
if(character == 9) {
for(int i=0; i<4; i++) {
writer.write((char)32);
}
} else {
writer.write((char)character);
}
}
writer.close();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
void main()
{
char str[] = {"\t asdonjawd \t "};
int i;
printf("%s\n", str);
for (i = 0; i < sizeof(str); i++)
{
if (str[i] == '\t')
{
str[i] = ' ';
}
}
printf("%s", str);
}
# Tab 문자(\t)를 4개의 공백문자로 바꾸는 소스코드
# source.txt의 내용은 임의로 정해두었다.
f1 = open("C:\doit\source.txt", 'r')
Tab = f1.read()
f1.close()
Space = Tab.replace("\t"," "*4)
f2 = open("C:\doit\source.txt",'w')
f2.write(Space)
f2.close()
def file_tap2space(fname):
with open(fname, "r", encoding = "UTF8") as f:
data = f.read()
data = data.replace("\t", " "*4)
with open(fname, "w", encoding = "UTF8") as f:
f.write(data)
return data
def replace_(x):
tap = "\t"
while True:
if tap in x:
x = x.replace("\t"," ")
else:
break
return x
code = "Life\tis\ttoo\tshort"
code1=replace_(code)
print(code1)
import sys
f = sys.open("SourceCode.py", "r")
input = list(f.read())
f.close()
f = sys.open("SourceCode.py", "w")
f.write(input.replace("\t", " "))
f.close()
import sys
def change_sentence(sentence):
sentence.replace('\t', " ")
return sentence
txt_file = sys.argv[1]
new_file = sys.argv[2]
f = open(txt_file)
sentences = f.read()
change_sentence(sentences)
n = open(new_file,'w')
n.write(sentences)
f.close()
n.close()
실행은 python code.py file1.txt file2.txt 입니다.
```{.python}
```filename = input('') tempfile=open(filename) tempfile=tempfile.read() newfile=tempfile.replace('\t', ' ') tempfile=open(filename, 'w') tempfile.write(newfile) tempfile.close()
filename=input("파일 이름을 입력해주세요 : ")
tempfile=open(filename)
tempfile=tempfile.read()
tem_str=tempfile.replace("\t"," ")
tempfile=open(filename,'w')
tempfile.write(tem_str)
tempfile.close()
python 3.7
fn=input('파일 이름: ')
with open(fn) as f:
with open('(new)'+fn,'w') as nf:
nf.write(f.read().replace('\t',' '*4))
f=open("tab_code.txt")
tab_content=f.read()
f.close()
space_content=tab_content.replace("\t"," "*4)
f=open("tab_code.txt",'w')
f.write(space_content)
f.close()
public class Solution {
public String solution(String str) {
String answer = "";
answer = str.replace("\t", " ");
return answer;
}
}
모든 \t을 space공백( ) 4칸으로 replace
def solution(msg):
answer = ""
answer = msg.replace("\t", " ")
return answer
msg = "이것은\tTab 키를 이용한\t문제이다."
print(solution(msg))
replace를 이용하여 space공백( ) 4칸으로 수정
try:
f = open("N:/Python/data/project/연습org.txt",'r')
lines = f.readlines()
f.close()
f = open("N:/Python/data/project/연습.txt","w")
for line in lines:
f.write(line.replace("\t"," "*4))
f.close()
except FileNotFoundError:
print("파일을 찾을 수 없습니다!")
finally:
pass
A씨는 개발된 소스코드를 특정업체에 납품하려고 한다. 개발된 소스코드들은 탭으로 들여쓰기가 된것, 공백으로 들여쓰기가 된 것들이 섞여 있다고 한다. A씨는 탭으로 들여쓰기가 된 모든 소스를 공백 4개로 수정한 후 납품할 예정이다.
A씨를 도와줄 수 있도록 소스코드내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램을 작성하시오.
function replaceTapToSpace(str){
return str.replace(/\t/g, " ")
}
replaceTapToSpace("이문장뒤에탭을칠거다 탭")
stringlist = list(input().split('\t'))
print(' '.join(stringlist))
또는
liststring = input()
liststring.replace('\t',' '*4)
print(liststring)
또는
stringlist = list(input().split('\t'))
print(' '.join(stringlist))
import re
with open('1.txt', 'r') as rfile, open('2.txt', 'w') as wfile:
wfile.write(re.sub('\t', ' '*4, rfile.read()))
def chapter01():
Str = input()
count = 0
for i in range(len(Str)):
if Str[i]=='\t':
count += 1
Str = Str.replace("\t", " ")
print("Here's correct senctence: ",Str)
print("Also I can see ", count, "character(s)")
answer = input('Would you try again?')
if answer == "Y" or answer == 'y':
chapter01()
else:
return
chapter01()
파이썬 3.7 기준으로 짠 것입니다. 참고로 재귀함수 호출 방식으로 프로그램을 작성해보았습니다.
python
f1=open("filename",'r')
data=f1.read()
rdata=data.replace('\t',' ')
f2=open("filename2",'w')
f2.write(rdata)
f.close()
def converter(src): # src: 입력받을 소스코드
with open(src, 'r') as f:
body = f.read() # body 변수에 소스코드 본문을 저장
body_new = body.replace("\t", " ")
with open(src, 'w') as f:
f.write(body_new)
src = input("소스코드 명을 입력해주세요(ex. test.txt): ")
converter(src)
파이썬으로 연습해봤습니다~
input_data=tuple(str(input("소스코드를 입력하세요")))
join_code=[]
for cnt in input_data:
if cnt =="\t":
join_code.append(' ')
else:
join_code.append(cnt)
print("".join(join_code))
with open("source4Tab2Blank.txt","r") as f:
r = f.read()
j = r.replace("\t"," "*100) #확인하기 편하게 극단적으로
print(j)
with open("replace.txt","w") as z: #터미널 확인용
z.write(j)
with open("replace.txt","r") as z: #터미널 확인용
g = z.read()
print("="*35,"절취선","="*35)
print(g)
>>> import sys
src=sys.argv[1]
dst=sys.argv[2]
f=open(src)
tab_content=f.read()
f.close()
space_content=tab_content.replace("\t"," "*4)
f=open(dst, 'w')
f.write(space_content)
f.close()
f = open("./source.txt","r") f2 = open("./source2.txt","w") lines = f.readlines() for line in lines: print(line) temp = '' if line[0:1] == ' ': temp = ' ' + temp for l in line: if l == ' ': pass else: temp = temp + l else: temp = line f2.write(temp) f.close() f2.close()
f=open('./source.txt','r')
source = f.read()
f.close()
f=open('./source.txt','w')
f.write(source.replace("\t"," "))
f.close()
#디렉터리 탐색
def fileTab2Space(fname):
with open(fname, 'r', encoding='UTF8') as f:
data = f.read()
with open(fname, 'w', encoding='UTF8') as f:
data = data.replace('\t', ' '*4)
f.write(data)
return data
import os
_dir = input("_dir: ") #dir = C:\\Users\\Administrator\\PycharmProjects\\CodingDojang
ext = input("ext: ")
for root, dirs, files in os.walk(_dir):
for file in files:
if file.endswith(ext): #확장자 검사
print(fileTab2Space(root + '\\' + file))
with open("source4Tab2Blank.txt", 'r') as sourceText :
originalText = sourceText.read()
print("* 원본 문서 *\n", originalText, "\n")
resultText = ''
for i in originalText :
if i == "\t" :
resultText += ' '
else :
resultText += i
print("* 수정 문서 *\n", resultText, "\n")
filename = input('Enter your file name: ')
tempfile = open(filename)
tempfile = tempfile.read()
temp_str = tempfile.replace('\t', ' ')
tempfile = open(filename, 'w')
tempfile.write(temp_str)
tempfile.close()
f=open('test.txt','r') line=f.read() f.close()
t=line.replace('\t',' ')
f.open('test.txt','w') f.write(t) f.close()
int main() {
char buffer[30];
char result[100] = { 0. };
int len = 0, i = 0, j = 0;
FILE *fp, *fp2;
fp = fopen("hello.txt", "r");
fp2 = fopen("hello2.txt", "w");
fgets(buffer, 30, fp);
while (len < 30) {
if (buffer[len] == 0)
break;
len++;
}
for (i = 0; i < len; i++) {
if (buffer[i] == '\t')
buffer[i] = ' ';
}
i = 0;
while (i<len) {
if (buffer[i] != ' ') {
result[j] = buffer[i];
j++; i++;
}
else {
result[j] = buffer[i];
result[j + 1] = ' ';
result[j + 2] = ' ';
result[j + 3] = ' ';
j += 4; i++;
}
}
fputs(result, fp2);
fclose(fp);
fclose(fp2);
}
def fileTab2Space(fname):
f = open(fname, "r", encoding = "UTF-8")
data = f.read()
f.close()
return data.replace("\t", " "*4)
file_name = input("파일 이름을 입력하세요")
replace_data = fileTab2Space(file_name)
print(replace_data)
Python
import sys
src = sys.argv[1]
dst = sys.argv[2] #src에서 읽어오고 수정한 내용은 dst에 저장
f=open(src,'r')
tab_content = f.read()
f.close() #tab이 포함된 텍스트를 tab_content에 저장
new_content = tab_content.replace("\t"," "*4)
f=open(dst,'w')
f.write(new_content)
f.close()
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0)
sum += i;
}
cout << "1000 미만 3과 5의 배수의 합 : " << sum << endl;
return 0;
}
file_name = input('enter input file name =') new_file_name = "new_"+ file_name
old_file = open(file_name, 'r') print('old_file:',old_file) # 중간에 확인을 위해 진행하는 값을 출력함
file_content = old_file.readlines() print('file_content:',file_content) # 중간에 확인을 위해 진행하는 값을 출력함
new_file = open(new_file_name,'w')
for i in file_content: result = i.replace('\t','____') new_file.write(result) old_file.close() new_file.close()
def tab_to_4space(string) :
return string.replace('\t', ' ')
print(tab_to_4space('\t\t\ttest\tstring\t\t'))
public class Main {
public static void main(String[] args) {
// 탭 키를 4칸뛰우기로 변경하는 코드(4 space)
String text = "안녕하세요 ";
text = text.replace(" ", " ");
System.out.println(text);
}
}
f = open("D:/src.py", 'r')
lines = f.readlines()
src = ''
for line in lines:
src += line
f.close()
src = src.replace("\t", " ")
f = open("D:/src.py", 'w')
f.write(src)
f.close()
import sys
with open(sys.argv[1],'r') as file:
tab = file.read()
with open(sys.argv [1],'w') as file:
file.write(tab.replace('\t',' '*4))
Data = 입력받는 문자열 Result = 변환되어 사용자에게 리턴시켜주는 문자열
Data = input("Please Enter the Text : ")
Result = Data.replace(" "," ")
print(Result)
my_file = input("Enter your file name : ")
#You must enter the file name extension!
f = open(my_file, "r")
data = f.read()
new = data.replace("\t"," ")
f.close()
f = open(my_file, "w")
f.write(new)
f.close()
with open('hello.txt', 'r') as file1: #탭으로 짜여진 소스코드를 불러온다
str1 = file1.read()
strCh = str1.replace('\t',' ') #탭을 공백4개로 변환
with open('hello_modify.txt', 'w') as file2: #변환된 내용저장하기 위한 hello_modify.txt 파일 생성
str2 = file2.write(strCh) # 변환된 내용을 hello_modify.txt 에 저장
filename = input('파일 이름을 입력하세요 :')
with open(filename, 'r') as f:
data = f.read()
data.replace('\t', ' ')
with open(filename, 'w') as f:
f.write(data)
import os
import subprocess as sp
filepath = input("파일이 위치한 경로를 입력하세요(파일명 포함) : ")
ext = input("확장자를 입력하세요 : ")
with open("filepath", 'r') as f:
srcContent = f.read()
with open("filepath", 'w') as taptospace:
taptospace.write(srcContent.replace("\t"," "))
import re
import sys
def tabToSpace():
print "file name" % sys.argv[0]
try : f = open(sys.argv[1])
except : tabToSpace(); sys.exit(2)
code = f.read()
f.close()
changedCode = code.replace("\t", " "*4)
f = open(sys.argv[1] , 'w')
f.write(changedCode)
f.close()
function removeTab(targetString) {
return targetString.replace(/\t/gi, " ");
}
function removeTab(targetString) {
return targetString.split("\t").join(" ");
}
python3.6.7
import sys
input_file = sys.argv[1]
output_file = sys.argv[2]
fi = open(input_file, 'r')
tab_contents = fi.read()
fi.close()
space_contents = tab_contents.repalce('\t', ' '*4)
fo = open(output_file, 'w')
fo.write(space_contents)
fo.close()
a = open("before.txt", "r")
data = a.read()
a.close()
b=open("after.txt", "w")
b.write(data.replace("\t", " "*4))
b.close()
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
f = open(dst, 'w')
f.write(space_content)
f.close()
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void main()
{
string filePath;
cout << "변환할 파일 경로 : ";
std::getline(std::cin, filePath);
ifstream fileIn(filePath);
ofstream fileOut(filePath+".convert");
char ch;
while (!fileIn.eof())
{
ch = fileIn.get();
if (ch == '\t')
fileOut << " ";
else
fileOut << ch;
}
}
def fileTap2Space(fname):
with open(fname,'r') as f:
data = f.read()
data = data.replace('\t',' ')
# 백업파일 이름 생성
l = len(ext)
a = fname[:-l]
# 백업파일 생성
with open(a + "_bak.txt",'w') as f:
f.write(data)
return data
'''
with as 구문
f.close필요 없음
자동으로 구문이 끝나면 f.close수행
'''
import os
_dir = input("_dir:")
ext = input("ext:")
for root, dirs, files in os.walk(_dir):
for file in files:
if file.endswith(ext):
print(fileTap2Space(root+ '\\' + file))
# 재즐보프: 재미있게 즐기는 정보보안프로젝트! 코드 참고하였습니다.
# 백업파일 이름 부분만 추가한 코드입니다
a=input('')
file=open('code.txt','w')
file.write(a)
file.close()
readfile=open('code.txt','r')
t=readfile.read()
t=t.replace('\t'," "*4)
readfile.close()
print(t)
strList = []
with open('./tab.txt') as f:
for s in f.readlines():
strList.append(s.replace('\t', ' '))
with open('./space.txt', 'w') as f:
for s in strList:
f.write(s)
Python3
tab.txt에 있는 탭 문자를 공백 4개로 바꿔서 space.txt에 저장합니다.
f = open('<source file path>', 'r')
fileContent = f.read()
f.close()
inputContent = fileContent.replace("\t", " "*4)
f = open('<source file path>', 'w')
f.write(inputContent)
def filetabReplace(fileNm):
with open(fileNm, "r", encoding="UTF-8") as f:
data = f.read()
data = data.replace("\t", " " * 4)
with open(fileNm, "w", encoding="UTF-8") as f:
f.write(data)
print(filetabReplace("file.py"))
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
f = open(dst, 'w')
f.write(space_content)
f.close()
교재 참고하였습니다.
with open('test.txt','r') as fs:
lines = fs.readlines()
with open('result.txt','w') as fw:
for line in lines:
i=0
c=line[0]
while ord(c) == 9:
line = line[0:i] + ' '*4 + line[i+1:]
i+=1
c = line[i]
fw.write(line)
#! python3
import sys
sourceFile = open(sys.argv[1], 'r')
content = sourceFile.read()
sourceFile.close()
tabToSpace = content.replace('\t', ' ' * 4)
updatedFile = open(sys.argv[2], 'w')
updatedFile.write(tabToSpace)
updatedFile.close()
def tab_to_space(s):
s=s.replace('\t', ' '*4)
return s
f=open('code.txt', 'r')
lines=f.readlines()
for line in lines:
line = tab_to_space(line)
f.write(line)
f.close()
static void Main(string[] args)
{
string Path = @"C:\Test.txt";
string [] ReadText = File.ReadAllLines(Path);
StreamWriter WriteText = new StreamWriter(Path);
foreach (string TextConvert in ReadText)
{
string Line = TextConvert.Replace("\t", " ");
WriteText.WriteLine(Line);
Console.WriteLine(Line);
}
WriteText.Close();
}
f = open("013.txt", 'r')
tap = f.read()
f.close()
space = tap.replace("\t", " "*4)
f = open("013.txt", 'w')
f.write(space)
f.close()
file = input('경로+이름+확장자 : ')
f = open(file, 'r')
f = f.read()
f_str = f.replace('\t',' ')
f = open(file, 'w')
f.write(f_str)
f.close()
PHP
// 임의 문자 생성
$str = "";
foreach(range(1, 10) as $n) {
$str.= str_repeat("\t", $n)."tab{$n}\n";
}
// 탭 -> 공백 치환
$result = str_replace("\t", str_repeat(" ", 4), $str);
print_r($result);
String = str(input("입력하세요 : "))
def tab_to_spaces(text): return text.replace("\t"," ")
print(tab_to_spaces(String))
#탭을 공백 문자로 바꾸기
f = open("tab.txt",'w')
data = r"DH\t:파이썬 잘하고 싶다.\t코딩은 어려워"
f.write(data)
f.close()
f = open("tab.txt", 'r')
line = f.read()
replace1 = line.replace(r'\t',' ')
print(replace1)
f.close()
public class 탭을공백문자로바꾸기 {
public String solution(String s) {
String answer = s.replaceAll("\t", " ");
return answer;
}
public static void main(String[] args) {
탭을공백문자로바꾸기 a = new 탭을공백문자로바꾸기();
System.out.println(a.solution("안녕하세요\t여러분\t제품소개\t입니다.\n잘부탁드립니다.\t지나가는\t이\t올림"));
}
}
def replace_indent(target_str):
if(target_str[0] == '\t'): return (' ' * 4) + target_str[1:]
else: return target_str
public class TabToSpace {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
str.replaceAll("\t", " ");
System.out.println(str);
}
}
import java.util.Scanner;
public class TapQuiz { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
String ans = "테스트1\t테스트2\t테스트3";
System.out.println("변환 전 =>" + ans);
ans = ans.replace("\t", " ");
System.out.println("변환 후 =>" + ans);
}
}
import java.util.Scanner; //Scanner기능을 사용하기위해 필요함.
public class Replace {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.nextLine(); //입력값을 문자로 받았다.
a=a.replaceAll("\t", " "); //replaceAll을 이용하여 \t(tab)을 공백으로 바꿨다.
System.out.println(a); //값을 출력
}
}
public class Sat1109 {
public static void main(String[] args) {
String str = "abcde\tfghij\tabc\ted\tff";
str = str.replaceAll("\t", " ");
System.out.println(str);
}
}
fname = "abc.py"
fname_new = "[MOD]" + fname
src_str = '\t'
chg_str = ' '*4
f = open(fname, 'r', encoding='UTF8')
f_str = f.read()
f.close()
f_str = f_str.replace(src_str,chg_str)
# print(f_str)
f = open(fname_new, 'w',encoding='UTF8')
f.write(f_str)
f.close()
python 3.7.2 / UnicodeDecodeError 고려 / 교육용 -코딩프렌즈-
f1 = open('new.txt', 'r')
data = f1.read()
f1.close()
data.replace('\t', ' '*4)
f2 = open('code.txt', 'w')
f2.write(data)
f2.close
a.txt를 읽어서 탭을 스페이스 4개로 바꾸고 b.txt로 저장하도록 만들어봤습니다.
f = open('a.txt','r')
content = f.read()
f.close()
con_new = content.replace('\t',' '*4)
f = open('b.txt','w')
f.write(con_new)
f.close()
#include <stdio.h>
int main(){
char tab[] ="apple\tbanana\tpineapple\tmelon\twatermelonasdasdasdasdasdasdasdasdsdasd\tasdasdasdasdasda";
int i,j,x=0;
int a = sizeof(tab);
for(i=0;i<a;i++){
if(tab[i]=='\t')
{
x++;
for(j=0;j<=a-i+2*x;j++){
tab[a+4+2*x-j]=tab[a+1+2*x-j];
}
for(j=0;j<4;j++){
tab[i+j]=' ';
}
}
}
printf("%s",tab);
return 0;
}
sample_txt = '''
안녕하세요. 탭테스트
안녕히가세요. 공백 4개 테스트
'''
def tabtos4(txt):
ans_txt = sample_txt.replace('\t', ' ')
print(ans_txt)
tabtos4(sample_txt)
파이선3.6 파일처리 생략
가장 단순?하게 작성하였습니다.
#Chang Tab to 4Spaces
strIn = input('파일이름을 입력하세요 :: ')
strOut = strIn + '_out.txt'
f = open(strIn, 'r')
before = f.read()
f.close()
after = before.replace('\t',' ')
f = open(strOut,'a')
f.write(after)
f.close()
print('%s 파일이 생성되었습니다' % strOut)
a=open("파일명.txt","r")
b=open("수정.txt",'w')
while True:
line=a.readline()
mod_line=line.replace(" "," ")
b.write(mod_line)
if not line:break
b.close()
void tab_to_space(char*original) { for (int i = 0; i < sizeof(original); i++) { if (original[i] == '\t') { original[i] = ' '; } } }
void main() { char tmp[] = "Hello, world! I am ANG JAE"; tab_to_space(tmp); printf("%s", tmp); }
f = open(tab_file)
tab_content = f.read()
f.close()
space_convert = tab_content.replace("\t"," "*4)
f.open(space_file,'w')
f.write(space_file)
f.close()
mix_code = "tab\ttab space space"
print(mix_code)
mix_code = mix_code.replace('\t','')
print(mix_code)
f1 = open("a.txt", 'w')
data = ("Life\tis\ttoo\tshort\nYou\tneed\tpython")
f1.write(data)
f1.close()
f1 = open("a.txt", 'r')
tab_content = f1.read()
space_content = tab_content.replace("\t", " "*4)
f1.close()
f2 = open("b.txt", 'w')
f2.write(space_content)
f2.close()
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
print(space_content)
class Program
{
static string start = "\t안녕\t\t안녕안녕";
static void Main(string[] args)
{
string result = start.Replace("\t", " ");
}
}
import sys
tap_file = sys.argv[1]
space_file = sys.argv[2]
f = open(tap_file)
tap_content = f.read()
f.close()
space_content = tap_content.replace('\t',' '*4)
f = open(space_file, 'w')
f.write(space_content)
f.close()
f=open("file directory", 'r')
data=f.read()
f.close()
g=open("file directory", 'w')
data=data.replace("\t", " ")
g.write(data)
g.close()
file = input("enter file directory ")
read1 = open(file, 'r')
data = tuple(read1.read())
write1 = open(file, 'w')
for i in range(len(data)):
if data[i] == '\t':
write1.write(' ')
else:
write1.write(data[i])
write1.close()
with open(input('파일 이름을 입력하세요: ')) as f: contents = f.read()
contents = contents.replace('\t', ' '*4)
with open('result.txt', 'w') as f: f.write(contents)
import java.util.*;
public class jony { public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.nextLine();
a = a.replaceAll("\t", " ");
System.out.println(a);
} }
f = open("code.txt",'r')
data = f.read()
f.close()
datas = data.replace("\t"," "*4)
f=open('code.txt','w')
f.write(datas)
f.close()
sourcefile=open("source.py","r") writefile=open("new_source.py","w") while True: # line=sourcefile.readline() line=sourcefile.read() if not line: break line=line.replace("\t"," "*4) newLine=line.strip('\n') print(newLine) writefile.write(line) sourcefile.close() writefile.close()
f=open("test.txt",'r')
lines = f.readlines()
f.close()
f=open("test.txt",'w')
i=0
while i<len(lines):
if lines[i]==None:
break
lines[i]=lines[i].replace('\t',' ')
f.write(lines[i])
i+=1
f.close()
def g(filename):
f = open(filename, 'r')
data = f.read()
result = data.replace('\t', ' ')
f = open(filename, 'w')
f.write(result)
f.close()
print(result)
import sys
a=sys.argv[1]
b=sys.argv[2]
f=open(a)
atab=f.read()
f.close
bsp=atab.replace('\t',' ')
f=open(b,'w')
f.write(bsp)
f.close()
print(a)
print(b)
print(atab)
print(bsp)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TapToSpace4 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("D:/desktop/Java/1.Tap.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("D:/desktop/Java/2.Space.txt"));
String text;
while ((text = br.readLine()) != null) {
text = text.replaceAll("\t", " ");
bw.write(text + "\n");
}
br.close();
bw.close();
}
}
java
f = open("needfixed.txt",'r')
data = f.read()
f.close()
fixed = data.replace("\t", ' ')
f = open('needfixed.txt', 'w')
f.write(fixed)
f.close()
f = open('filename', 'r')
data = f.read()
f.close()
data_Replace = data.replace('\t', ' ')
f = open('filename', 'w')
f.write(data_Replace)
f.close()
#파이썬
fileName = input() #파일 이름 입력받기
try:
file = open(fileName,'r') #파일을 r(읽기) 형식으로 오픈
except FileNotFoundError: #파일이 존재하지 않는 경우
print('현재 디렉터리에 해당 파일이 존재하지 않습니다.')
filestr = input('파일에 쓰고자 하는 내용을 작성해 주십시오:')
file = open(fileName,'w')#파일 신규 생성
file.write(filestr)
file.close()
file = open(fileName,'r')
finally: #파일에
filestr = file.read()
file.close()
filestr = filestr.replace('\t',' ') #replace()를 이용해 filestr안의 \t문자를 ' '(공백문자 4개)로 변환
file = open(fileName,'w') #파일을 w(쓰기) 형식으로 오픈
file.write(str(filestr)) #변환한 내용을 파일에 덮어씀
file.close()
##########################################
print(f'{fileName}이 변환되었습니다---')
file = open(fileName,'r')
filestr = file.read()
print(filestr)
#파이썬
#역으로 공백 4개(' ')를 탭으로 변환해주는 프로그램
import re
try:
fileName = input() #파일 이름 입력받기
file = open(fileName)
except FileNotFoundError: #파일이 존재하지 않는 경우
print('현재 디렉터리에 해당 파일이 존재하지 않습니다.')
filestr = input('파일에 쓰고자 하는 내용을 작성해 주십시오:')
file = open(fileName,'w')#파일 신규 생성
file.write(filestr)
file.close()
file = open('fileName.txt')
finally:
filestr = file.read()
file.close()
x = re.compile('[ ]{4}')#공백 4개인 부분을 찾는 패턴 생성[정규표현식]
filestr = x.sub('\t',filestr)#sub함수를 이용해 x에 대해 TRUE가 반환되는 부분을 탭으로 변환
file = open(fileName,'w')
file.write(filestr)
file.close()
##########################################
print(f'{fileName}이 변환되었습니다---')
file = open(fileName,'r')
filestr = file.read()
print(filestr)
#파이썬
#텍스트 파일을 불러와서 변환후 화면으로도 출력을 하고
#파일로도 저장을 하는 소스입니다
import sys
fileopen=open("python.txt")
text=fileopen.read()
print ('원본텍스트\n',text)
replaced_text=text.replace('\t',' ')
print ('\n탭을 공백4칸으로 변환\n',replaced_text)
sys.stdout=open('python2.txt','w')
print(replaced_text)
import sys
with open(sys.argv[1],"r") as f:
lines=f.readlines()
for i,line in enumerate(lines):
lines[i]=line.replace(" \t"," ")
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "haha\tdodo\tqpqp";
while (str.find("\t") != string::npos) {
str = str.replace(str.find("\t"), 1, " ");
}
cout << str << endl;
return 0;
}
C++
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
String a="";
a = s.nextLine();
a = a.replace("\t", " ");
System.out.println(a);
}
public static String changeTabToSpace(String source) {
source = source.replaceAll("\t", " ");
return source;
}
file1 = open("test.txt", "r", encoding="utf-8")
text = file.read()
with open("foo.txt", "w", encoding="utf-8") as f2:
f2.write(text.replace("\t", " "))
import sys
import os
x = input("파일경로와 파일을 입력하세요 :")
filename = x
with open (filename) as file :
transform_file = file.read()
change = file.replace('\t'," ")
file = open(file,mode='w')
file.write(chage)
file.close()
import java.io.*;
import java.util.*;
public class tabchange {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Character> list = new LinkedList<Character>();
try {
FileReader fr = new FileReader("C:\\Users\\KK\\Desktop\\Study\\Test\\test.txt");
BufferedReader rd = new BufferedReader(fr);
FileWriter fw = new FileWriter ("C:\\Users\\KK\\Desktop\\Study\\Test\\output.txt");
BufferedWriter rw = new BufferedWriter(fw);
int check;
while( (check = rd.read()) != -1 ) {
char mo = (char)check;
if( mo == '\t') {
mo = ' ';
for(int i = 0 ; i < 4 ; ++i ) {
rw.write(mo);
//System.out.print(mo);
}
}
else {
rw.write(mo);
//System.out.print(mo);
}
}
fr.close();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
f=open('abc.txt','w')
f.write('my\tname\tis\tpython')
f.close()
f=open('abc.txt','r')
a=f.read()
f.close()
b=a.split()
c=' '.join(b)
f=open('abc.txt','w')
f.write(c)
f.close()
f = open("sample.txt")
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
f = open("sample_new.txt", 'w')
f.write(space_content)
f.close()
import java.util.Scanner;
public class Revision{
public static void main(String[] args){
String a = new Scanner(System.in);
a1 = a.replaceAll('\t', ' ');
System.out.print(a1);
Scanner.close();
}
}
이렇게 풀어봤습니다. replaceAll() 함수를 이용했습니다.
import glob
import re
import shutil
class DoConversion:
def __init__(self):
pass
def replaceTab(self):
b = glob.glob("*.src")
for i in b:
print(i)
f = open(i,"r")
t = open("temp.src","w")
while True:
line = f.readline()
if not line:
break
p = re.compile(r'\t')
m = p.search(line)
if m:
line = line.replace("\t"," ")
t.write(line)
f.close()
t.close()
shutil.move("temp.src",i)
a = DoConversion()
a.replaceTab()
파이썬입니다. 임의의 파일 'test_text.py' tab이 있는 for loop 의 짧은 코드입니다. f.read() 와 f.readlines() 차이는 아직 잘 모르겠네요. readlines()는 리스트로 돌려줘서 for loop을 통해 replace()를 써봤는데 바뀌지 않는것 같아 read()로 작성했습니다.
f = open('test_text.py', 'r+')
read = f.read()
temp_read = read.replace('\t', ' ')
new = open('new_read.py', 'w')
new.write(temp_read)
new.close()
f.close()
import tkinter as tk
from tkinter import filedialog
root=tk.Tk()
root.withdraw()
file_path=filedialog.askopenfilename()
f = open(file_path)
f1 = f.read()
f1 = f1.replace("\t", " ")
f = open(file_path, 'w')
f.write(f1)
f.close()
python 여러 파일이 있다고 가정한 후, replace 탭을 공백*2로 바꾸고, 체크하는 함수까지 넣어봤습니다.
실제로 들여쓰기 통일화를 위한 업무 자동화 코드를 짜야 한다면, 복잡해 질 것 같네요.
고수님들 코드 잘 보고 배워갑니다.
import os
# 지정한 패스의 모든 .py 파일 가져오기
def get_file_path():
pathlist = []
path = os.getcwd() + "/quiz/codingDojang/Python-Algorithm/002_source_code_file"
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith(".py"):
pathlist.append(root + "/" + file)
else: pass
return pathlist
# 파일 읽기, 수정하기, 저장하기
def file_read_write():
pathlist = get_file_path()
for path in pathlist:
new_lines = []
with open(path, "r") as f:
lines = f.readlines()
for line in lines:
new_lines.append(line.replace("\t", " "*4))
with open(path, "w") as f:
f.writelines(new_lines)
file_read_write()
def check_work():
pathlist = get_file_path()
for path in pathlist:
_file = open(path)
if _file.read().find("\t") != -1:
raise Exception("코드에 탭을 찾았습니다.")
else:
print("파일이 정상입니다. 검사 완료.")
package dojang;
import java.util.Scanner;
public class Replaceblackbox {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("글들을 넣어 보세요.");
String a=sc.nextLine();//next보다 nextline이 적합 엔터나 탭 잡아야 함
a=a.replace("\t"," ");
System.out.println(a);
}
}
package Practice;
public class TabToSpacebar {
public static void main(String[] args) {
String text = "Hi my name is Java\tI'm your friend\tand i'm so proud of you.";
System.out.println(text);
System.out.println(TabChanger(text));
}
private static String TabChanger(String text) {
String ChangeTab = text.replaceAll("\t", " ");
return ChangeTab;
}
}
filename=input("Enter your file name : ") tempfile=open(filename) tempfile=tempfile.read() temp_str=tempfile.replace("\t"," ") tempfile=open(filename,'w') tempfile.write(temp_str) tempfile.close()
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
f.open(dst, 'w')
f.write(space_content)
f.close
import sys
def tab2gap(i):
return i.replace("\t", " " * 4)
del sys.argv[0]
i = sys.argv[0]
o = sys.argv[1]
with open(i, 'r') as f:
with open(o, 'w') as f2:
f2.write(tab2gap(f.read()))
package codeDojang;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Prac {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("test.txt"));
} catch (FileNotFoundException e) {
System.out.println("경로에 파일이 존재하지 않습니다.");
}
String line = null;
String tmp="";
while((line = br.readLine())!=null) {
if(line.contains("\t")) {
tmp+=line.replace("\t", "....");
}
tmp+=line+"\n";
}
BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"));
bw.write(tmp);
bw.close();
}
}
공백대신 ....으로 표시함
File_Name=input("write your file name")
f.open(File_Name,"r")
data=f.read()
f.close()
data.replace("\t"," ")
import java.util.Scanner;
public class pro2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String b = a.replace("\t", " ");
System.out.println(a);
System.out.println(b);
}
}
a = input("소스코드를 텍스트 파일로 저장하고 저장경로를 입력하세요: ")
print(a)
with open("{}".format(a), 'r') as f:
lines = f.readlines()
print(lines)
with open("{}".format(a), 'w') as f:
for j in range(0, len(lines)):
data = lines[j].replace("\t", " ")
f.write(data)
print("소스코드 내 모든 \t을 공백4개로 바꾸었습니다. 저장된 파일을 복사하여 사용하세요.")
파이썬 3.7.2 버전입니다.
def foo():
file_name = input('파일명을 입력해 주십시오 : ')
row_file = open(file_name, 'r', encoding = 'UTF-8')
lines = row_file.readlines()
row_file.close()
modify_lines = [line.replace('\t', ' '*4) for line in lines]
modify_file = open('modify_'+file_name, 'w', encoding = 'UTF-8')
for line in modify_lines:
modify_file.write(line)
modify_file.close()
foo()
파이썬입니당
files=input('파일경로:')
with open(files,'r') as f:
text=f.read()
text=text.replace('\t',' ')
with open(files, 'w') as f:
f.write(text)
def howmanyT(word):
count = 0
store1 = []
store2 = []
new = ''
for i in range(0, len(word)):
if word[i] == '\t':
count += 1
store1.append(i)
if store1 == [] and count == 0:
return word
elif store1 != []:
for b in range(len(word)):
store2.append(word[b])
for c in store1:
store2[c] = ' '
for d in store2:
new += d
return new
def tabtoSpace(filename):
store = []
for i in open(filename, 'r'):
edited = ''
line = i.split(' ')
for w in line:
edited += howmanyT(w) + ' '
edited = edited[0:len(edited)-1]
store.append(edited)
f1 = open(filename, 'w')
for i in store:
f1.write(i)
print('complete')
tabtoSpace('test1.txt')
name =input("파일 이름을 입력하세요.: ")
text = open(name)
text_ =text.read().replace('\t',' ')
text= open(name,'w')
text.write(text_)
text.close()
import sys
name1 = sys.argv[1]
name2 = sys.argv[2]
f = open(name1,'r')
all = f.read()
f.close()
all = all.reaplce('\t',' ' * 4)
f1 = open(name2,'w')
f1.write(all)
f1.close()
f = open("tab_content.txt", "r")
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t"," ")
f = open("space_content.txt", "w")
f.write(space_content)
f.close()
파이썬으로 작성했습니다.
작성된 코드를 tab_content.txt로 가정하고 코딩하였습니다.
with open('bbb.txt', 'w') as file:
with open('aaa.txt', 'r') as f:
for line in f.readlines():
line = line.replace('\t', ' ')
file.write(line)
[파이썬]
before = open("C:/Users/Home/Desktop/tab.txt", 'r')
after = open("C:/Users/Home/Desktop/4space.txt", 'w')
tab_contents = before.readlines()
for i in tab_contents:
j = str(i) # 요소를 str로 바꾸고
k = j.replace("\t", " ") # 탭을 스페이스 4번으로 바꾼 뒤 k에 저장해줍니다
after.write(k) # 바꾼 k의 내용을 4space.txt에 써줍니다
before.close()
after.close()
public class mate {
public static void main(String[] args) {
String text = "Hello\tmy\tname\tis";
text = text.replaceAll("\t", " ");
System.out.println(text);
}
}
def replace(filename, original = "\t", replaced = " "):
with open("filename", "r") as f:
codes = f.read()
codes.replace(original, replaced)
with open("filename"+"_rep", "w") as f_:
f_.write(codes)
<파이썬 3>
def tab_convert_to_space4(filename):
open_file = open(f"{filename}.txt", 'r', encoding='utf8')
allfile = open_file.read()
allfile = allfile.replace("\t",' ')
open_file.close()
writefile = open(f'{filename}_invert.txt', 'w', encoding='utf8')
writefile.write(allfile)
writefile.close()
def tab_convert_to_space4(filename):
open_file = open(f"{filename}.txt", 'r', encoding='utf8')
allfile = open_file.read()
allfile = allfile.replace("\t",' ')
open_file.close()
writefile = open(f'{filename}_invert.txt', 'w', encoding='utf8')
writefile.write(allfile)
writefile.close()
String filePath = "C:\\home\\test.txt";
//파일 객체 생성
File file = new File(filePath);
String strText = "";
int nBuffer;
//파일 읽기
try{
BufferedReader buffRead = new BufferedReader(new FileReader(file));
while((nBuffer = buffRead.read()) != -1){
strText += (char)nBuffer;
}
buffRead.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(strText);
//파일이 없을경우 파일생성
if(file.exists() == false) {
try {
int nLast = filePath.lastIndexOf("\\");
String strDir = filePath.substring(0, nLast);
String strFile = filePath.substring(nLast+1, filePath.length());
File dirFolder = new File(strDir);
dirFolder.mkdirs();
File f = new File(dirFolder, strFile);
f.createNewFile();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
//파일 수정
try {
BufferedWriter buffWrite = new BufferedWriter(new FileWriter(file));
String Text = strText.replace("\t", " ");
buffWrite.write(Text, 0, Text.length());
buffWrite.flush();
buffWrite.close();
}catch (Exception e) {
System.out.println(e.getMessage());
}
python 3.9입니다. 실행할 때 python example.py (탭 파일 디렉토리) (공백 파일 디렉토리) 식으로 실행합니다. 소스:
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src, 'r')
body = f.read()
f.close()
replaced = body.replace('\t', ' '*4)
f2 = open(dst, 'w')
f2.write(replaced)
print('processed successfully')
실행법:
C:\Users\82105>cd C:\Users\82105\Desktop\이준우\python\simple_programs\codingdojang
C:\Users\82105\Desktop\이준우\python\simple_programs\codingdojang>python coding19.py C:\Users\82105\Desktop\이준우\python\simple_programs\tab.txt C:\Users\82105\Desktop\이준우\python\simple_programs\four_space.txt
processed successfully
C:\Users\82105\Desktop\이준우\python\simple_programs\codingdojang>
tab.txt 내용: (각 공백은 탭 문자)
1 2 3 4 5
four_space.txt 내용: (각 공백은 스페이스 4개)
1 2 3 4 5
tab과 공백4칸의 차이인 2칸을 lstrip으로 없애주고 다시 2칸을 전체에 들여쓰기 해보았습니다.
renew = sourcecode.lstrip(" ") print(" ",renew)
파이썬 시작한지 얼마 되지않아 이런 간단한 코드로 밖에 못쓰겠네요 ㅠ
a = "\t" * 4
if a == "\t" * 4:
a = end=" " * 4
print(a)
# a = end=" "
# print((a+".")*4)
py=input("file name : ")
with open(py, 'r') as f:
data = f.read()
f1 = data.replace("\t", " ")
with open(py, 'w') as f:
f.write(f1)
f = open('file.txt','r')
body = f.read()
f.close()
body = body.replace('/t',' ')
f = open('file.txt','w')
f.write(body)
f.close()
#coding_dojang: tabto4
def tabto4(file):
result = ''
with open(file, 'r') as fr:
result = fr.read()
with open(file, 'w') as fw:
fw.write(result.replace('\t', ' '))
tabto4(filename)
a = open('tab','r') b = a.readlines() a.close()
c = b.replace("\t"," ") a = open('tab','w') a.write(b) a.close
public static void main(String[] args) {
String inputData = "테스트 테스트 테스트 테스트 ";
System.out.println(test(inputData));
}
public static String test(String inputData) {
return inputData.replaceAll("\t", " ");
}
filename = input("파일 이름을 입력하세요: ")
file = open(filename, 'r')
file = file.read()
newFile = file.replace("\t", " "*4)
file = open(filename, 'w')
file.write(newFile)
file.close()
import sys
src = sys.argv[1]
dst = sys.argv[2]
with open(src, 'r') as f:
lines = f.readlines()
newline = []
for line in lines:
if line[0] == "\t":
newline.append(" " + line[1:])
else:
newline.append(line)
with open(dst, 'w') as f:
f.writelines(newline)
package exam;
public class Ex03 {
public static void main(String[] args) {
String str = "public\tstatic\tvoid\tmain";
System.out.println(str);
str = str.replaceAll("\t", " ");
System.out.println(str);
}
}
java
from os import replace
a = str(input('수정할 파일 이름 : ',))
b = str(input('저장할 파일 이름 : ',))
f = open(a, 'r', encoding='UTF-8')
line = f.read()
filetext = line.replace('\t',' '*4)
f.close()
f = open(b, 'w', encoding='UTF-8')
f.write(filetext)
f.close()
with open('txt','r') as file:
line = file.read()
line = line.replace("\t", " ")
with open('txt', 'w') as file2:
file2.write(line)
<script>
let str ="apple, ,banana, orange, ,banana";
let replaced_str=str.replace(/ /gi,"tomato");
console.log(replaced_str)
</script>
package test1;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
System.out.print("소스코드 입력 : ");
Scanner sc = new Scanner(System.in);
String sourceCode = sc.next();
sourceCode.trim();
String finalCode = " " + sourceCode;
System.out.println(finalCode);
sc.close();
}
}
# replace 1 tap with 4 spaces
code = input("코드를 입력하세요.")
temp = code.split("\t")
print(temp)
# f = open("file name")
# code = f.read()
code.replace("\t", " ")
code = code.split("\t")
print(code)
filename=input("Enter your file name : ") tempfile=open(filename) tempfile=tempfile.read() temp_str=tempfile.replace("\t"," ") tempfile=open(filename,'w') tempfile.write(temp_str) tempfile.close()
public static void main(String[] args) {
String str = "\t안녕\t";
System.out.println(str);
str = str.replace("\t", " ");
System.out.println(str);
}
import os
def tab2space(fname):
with open(fname, 'r', encoding='UTF8') as f:
data = f.read()
data = data.replace('\t', ' '*4)
with open(fname, 'w', encoding='UTF8') as f:
f.write(data)
dir_ = input('dir_: ')
ext = input('ext: ')
for root, dirs, files in os.walk(dir_):
for file in files:
if file.endswith(ext):
print(tab2space(root + '/' + file))
import sys
src = sys.argv[1] # 탭을 포함하고 있는 파일명
dst = sys.argv[2] # 탭을 공백 4개로 변환한 결과를 저장할 파일명
f = open(src)
tab_contest = f.read()
f.close()
space_content = tab_content.replace("\t", " " *4)
f = open(dst, 'w')
f.write(space_content)
f.close()
name = input("파일 경로를 입력하세요:")
f = open(name)
f = f.read()
f_str = f.replace('a','b')
f = open(name,'w')
f.write(f_str)
f.close()
python입니다.
def Tab(i):
Space=i.replace(' ',' ') and i.replace('\t',' ')
return Space
a="Hello Hi\tbye"
print(Tab(a))
public class Ex02 {
public static void main(String[] args) {
String str = "ABCD EFGF sd";
tab(str);
}
static void tab(String doc) {
doc = doc.replaceAll("\t", " ");
System.out.println(doc);
}
}
path = input("open 할 file 입력 : ")
f = open(path,'r')
data = f.read()
data.replace('\t',' ')
f.close()
f = open(path.'w')
f.write(data)
f.close()
import sys
src = sys.argv[1]
dst = sys.argv[2]
f = open(src)
tab_content = f.read()
f.close()
space_content = tab_content.replace("\t", " "*4)
f = open(dst, 'w')
f.write(space_content)
f.close()
파이썬입니다 import sys
f = open("/Users/tastebread/PycharmProjects/a.txt",'r') tab_content = f.read() f.close()
space_content = tab_content.replace("\t"," "*4) print(space_content)
fileOne = open('file1.txt','r')
fileTwo = open('file2.txt','w')
data = fileOne.read()
data = data.replace('\t',' ')
fileTwo.write(data)
fileOne.close()
fileTwo.close()
package com.algorithm.algorithmpractice.dojang;
public class tabtospace {
// A씨는 개발된 소스코드를 특정업체에 납품하려고 한다.
// 개발된 소스코드들은 탭으로 들여쓰기가 된것, 공백으로 들여쓰기가 된 것들이 섞여 있다고 한다.
// A씨는 탭으로 들여쓰기가 된 모든 소스를 공백 4개로 수정한 후 납품할 예정이다.
// A씨를 도와줄 수 있도록 소스코드내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램을 작성하시오.
public static void main(String[] args) {
String code = "\t1\t123\tzas\tdfd\tasf\tas\tdf";
String result = code.replace("\t", " ");
System.out.println(result);
}
}
path=input() file=open(path, 'r', encoding="UTF8") lines=file.readlines() for line in lines: line=line.replace("\t", " ") print(line) file.close()
int c;
while ((c = getchar()) != EOF)
{
if (c != '\t')
{
putchar(c);
}
if (c == '\t')
{
printf(" ");
}
}
public static void main(String[] args) {
/* *문제*
A씨는 개발된 소스코드를 특정업체에 납품하려고 한다.
개발된 소스코드들은 탭으로 들여쓰기가 된것, 공백으로 들여쓰기가 된 것들이 섞여 있다고 한다.
A씨는 탭으로 들여쓰기가 된 모든 소스를 공백 4개로 수정한 후 납품할 예정이다.
A씨를 도와줄 수 있도록 소스코드내에 사용된 탭(Tab) 문자를 공백 4개(4 space)로 바꾸어 주는 프로그램을 작성하시오. */
String str = "\t";
System.out.println(str);
str.replaceAll("\t", " ");
System.out.println(str);
} // main
맞는지 잘 모르겠습니다 코드보시고 리뷰좀해주세요ㅠ_ㅠ
# python
import sys
first = sys.argv[1]
second = sys.argv[2]
with open(first, "r") as f:
data = f.read()
with open(second, "w") as f:
data2 = data.replace("\t", " " * 4)
f.write(data2)
c#입니다. replace 안쓰고 싶어서 해봤어요
public static string Replace(string sentence)
{
// " " => " "
int cnt = 0;
StringBuilder text = new StringBuilder();
while (sentence.Length > cnt)
{
if (sentence[cnt] == '\t')
{
text.Append(" ");
}
else
{
text.Append(sentence[cnt]);
}
cnt++;
}
return text.ToString();
}
f1 = open("source_code.py", 'r')
f2 = open("source_code_new.py", 'w')
lines = f1.readlines()
for x in lines:
x = x.replace('\t', ' ') # 탭을 공백 4개로 바꾸기
print(x, file=f2)
f1.close()
f2.close()
file = input("파일 이름을 입력하세요.:")
try:
f = open(file, 'r')
except FileNotFoundError:
pass
file = input("파일을 읽을 수 없습니다. 파일 이름을 다시 입력하세요.:")
content = f.read()
change = content.replace('\t',' ')
f.close()
f = open(file, 'w')
changed = f.write(change)
f.close()
print("파일 내의 탭 문자가 공백 4개로 수정되었습니다.")
filename = '새파일.txt'
with open(filename, 'r') as f:
line = f.read()
with open(filename, 'w') as f:
f.write(line.replace('\t', ' '))
public class ReplaceTabWithSpace {
public void solution(String params) {
String[] tabArr = this.splitByTab(params);
String result = this.replaceTabWithSpace(tabArr);
System.out.println(result);
}
// ==== private ====
private String[] splitByTab(String str) {
String[] arr = str.split("\t");
return Arrays.stream(arr)
.filter(s -> s.length() > 0)
.toArray(String[]::new);
}
private String replaceTabWithSpace(String[] strArr) {
StringBuilder builder = new StringBuilder();
for (String s : strArr) {
builder.append(" ").append(s);
}
return builder.length() > 0 ? String.valueOf(builder) : "";
}
}
def tabToSpace4():
with open('source.txt','r') as f:
source=f.read()
with open('source.txt','w') as f:
changedSource=source.replace("\t", " ")
f.write(changedSource)
print(changedSource)
tabToSpace4()
write_f = open('./sample/content_with_whitespace.txt', 'w')
read_f = open('./sample/content_with_tab.txt', 'r')
write_f.write(re.sub("\t", ' '*4, read_f.read()))
read_f.close()
write_f.close()
'''
#make before code include tab
f=open("scr.txt",'w')
sourcecode="""
sum=0
for i in range(1000):
if i%3==0 or i%5==0:
sum+=i
print(sum)"""
f.write(sourcecode)
f.close()
'''
#read before code include tab
f=open("scr.txt",'r')
codeTab=f.read()
f.close()
print(codeTab)
#tab->space*4
codeSpace=codeTab.replace("\t"," "*4)
#revision
f=open("scr.txt",'w')
f.write(codeSpace)
f.close()
package test;
public class Ex14 {
public static void main(String[] args) {
String file = "";
replace(file);
}
public static String replace(String file) {
file.replace("\t", " ");
return file;
}
}
code = input('Q. 탭을 공백4개로 변경할 코드를 입력하세요: ')
code_rev = code.replace('\t', ' ')
print(code_rev)
public class Tab2Space {
public String convertTab2Space(String originStr){
String returnString = null;
if (originStr != null) {
returnString = originStr.replace("\t", " ");
}
return returnString;
}
}
f = open("./cord.txt.", 'r') #파일이름은 가정 lines = f.readlines() f.close() f = open("./revise.txt", 'w') #없으면 파일 생성 for line in lines: f.write(line.replace("\t", " ")) f.close()
f = open('file', 'r')
f_rev = open('file_rev', 'w')
lines = f.readline()
for line in lines:
line_rev = line.replace('\t', ' '*4)
f_rev.write(line_rev)
f.close()
f_rev.close()
with open('file','r') as f:
contents=f.read()
modified_cont=contents.replace('\t',' '*4)
with open('file','w') as f:
f.write(modified_cont)
f=open('a.txt','r',encoding='utf-8')
lines=f.readlines()
for line in lines:
line=line.strip()
line=line.replace('\t',' '*4)
print(line)
f.close()
public class SelfTest_2 {
public static void main(String[] args) {
String text = " tab change to space";
text = text.replace("\t", " ");
System.out.println(text);
}
}
package codingstamp.ex019_Lv1;
import java.util.Scanner;
public class trialAndError {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 우선 키보드 입력을 받아준다.
String str = sc.nextLine();
str = str.replace("\t", " ");
System.out.println(str);
}
}
def replace_tabs_with_spaces(input_file, output_file): with open(input_file, 'r') as file: source_code = file.read()
modified_code = source_code.replace('\t', ' ') # 탭을 공백 4개로 대체
with open(output_file, 'w') as file:
file.write(modified_code)
if name == "main": input_file = "input_source_code.txt" # 입력 파일의 이름을 여기에 지정 output_file = "output_source_code.txt" # 수정된 소스코드를 저장할 파일 이름을 여기에 지정
replace_tabs_with_spaces(input_file, output_file)
```{.python} str_src = "\tsome\tthing something \tsomething something\t something" revised_src = str_src.replace("\t"," ") print(revised_src) print(revised_src.find("\t"))
# 파일을 열기 -> replace('\t', ' '*4)사용 -> 새로운 파일에 저장
import os
def NO_tab(input_file, output_file):
with open(input_file, 'r') as f:
content = f.read()
just_spaces = content.replace('\t', ' ' * 4)
with open(output_file, 'w') as file:
file.write(just_spaces)
if __name__ == '__main__':
input_file = 'input_code_file.txt'
output_file = 'output_code_file.txt'
NO_tab(input_file, output_file)
indentTab2space = lambda x,w: len(x.split())>0 and x[:x.find(x.split()[0])].replace('\t',' '*w)+x[x.find(x.split()[0]):] or ''
print(indentTab2space('\t \tif 조건: print(" 테스트 탭\t테스트 ")', 4))
> if 조건: print(" 테스트 탭 테스트 ")
def replace_tabs_in_code(): import inspect
current_code = inspect.getsource(replace_tabs_in_code)
modified_code = current_code.replace('\t', ' ')
print("===== 수정된 코드 =====")
print(modified_code)```{.python}
```
def tab_to_4spaces() :
# input of the file name of the source code
file_name = input('Enter the file name : ')
# output of the original code
with open(file_name, 'r') as before :
original_code = before.read()
print('Original code is : \n', original_code)
# transformation of tab to 4 spaces
changed_code = original_code.replace('\t',' '*4)
# output of the transformed code
print('Changed code is : \n', changed_code)
print('\n')
# confirmation of the changed code
with open('changed_file.txt','w+',encoding='utf-8') as after :
after.write(changed_code)
after.seek(0)
print('In changed_file : ', after.read())
JAVA입니다.
package 탭을_공백_문자로_바꾸기;
import java.io.FileReader;
public class ReplaceTab {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
FileReader fr = new FileReader(ReplaceTab.class.getResource("code.txt").getPath());
while(true) {
int read = fr.read();
if(read == -1) {
break;
}
String s = Character.toString((char) read);
if(s.equals("\t")) {
s = " ";
}
System.out.print(s);
}
}
}
code="#include <stdio.h>\n\nint main(void)\n{\n printf(\"hello, world.\");\n\treturn 0;\n}"
print(code)
list_code=list()
for a in code:
if a=='\t':
list_code.append(' ')
else:
list_code.append(a)
print(list_code)
print(''.join(list_code))
import os
def replace_indent_tabs(path):
with open(path, "r", encoding="utf-8") as f:
lines = f.readlines()
new_lines = []
for line in lines:
idx = 0
while idx < len(line) and line[idx] == '\t':
idx += 1
indent_spaces = " " * idx
remainder = line[idx:]
new_lines.append(indent_spaces + remainder)
# 파일 덮어쓰기
with open(path, "w", encoding="utf-8") as f:
f.writelines(new_lines)